Reputation: 2405
I am quite new in Ruby so would like to know and learn how to DRY. I have 2 if statement that's very similar, is there anyway to refactor it?
msg1,msg2 = msg.split('.')
if !msg1.nil?
items = msg1.split(',')
items.each do |item|
item.strip!
end
somefunction(items)
end
if !msg2.nil?
items = msg2.split(',')
items.each do |item|
item.strip!
end
somefunction(items)
end
Upvotes: 0
Views: 145
Reputation: 5914
We can write the same in a single line.
message.split('.').each{|msg| somefunction msg.split(',').collect(&:strip) }
Upvotes: 1
Reputation: 66867
Looks like you can do away with the two variables:
msg.split('.').each do |msg|
items = msg.split(',').map(&:strip)
somefunction(items)
end
Edit: I removed the unless
since the array created by split
will not contain any. In your original code it made sense in case the array had 0 or 1 element, but by using each
this becomes unnecessary.
Upvotes: 4