Reputation: 817
How can I DRY out the following Ruby Code:
x = 'a random string to be formated'
x = x.split('^')[0] if x.include?('^')
x = x.split('$')[0] if x.include?('$')
x = x.split('*')[0] if x.include?('*')
I'm looking for the amazingly elegant ruby one liner but I'm having a hard time finding it. It should probably be somewhat readable though.
Thanks
Upvotes: 1
Views: 121
Reputation: 27247
You're looking for this regex:
string.match(/^([^^$*]+)[$^*]?/).captures[0]
It returns all characters up the the first occasion of $, ^, or *
, or the end of the string.
Upvotes: 0
Reputation: 11107
Based on the code you provided
x = 'a random string to be formated'
%w(^ $ *).each do |symbol|
x = x.split(symbol)[0] if x.include?(symbol)
end
Upvotes: 0
Reputation:
This works for me:
x = "a random string to be formatted"
['^', '$', '*'].each { |token|
x = x.split(token)[0] if x.include?(token)
}
Upvotes: 0