Reputation: 239
Ruby on Rails: from URL i want to get a specific value, for that one i am checking whether the url containing that value or not using an array. if it has that value i am splitting url and returning value.
@url = 'http://fruits.com/A15/abc1234-apple-w740_h550_q58.jpg'
['apple','banana','grape','butter','honey'].each do |fruit|
if (@url.include? fruit)
return @url.split(fruit)[1].freeze
end
end
i don't want to loop 5 times.. question is how can i compress this loop.
Upvotes: 1
Views: 82
Reputation: 114138
You could pass a regular expression to String#split
:
@url = 'http://fruits.com/A15/abc1234-apple-w740_h550_q58.jpg'
@url.split(/apple|banana|grape|butter|honey/)[1]
#=> "-w740_h550_q58.jpg"
Or, using String#[]
:
@url[/(apple|banana|grape|butter|honey)(.*)/, 2]
#=> "-w740_h550_q58.jpg"
Or, using a positive lookbehind to avoid the second argument: (hat tip to mudasobwa)
@url[/(?<=apple|banana|grape|butter|honey).*/]
#=> "-w740_h550_q58.jpg"
Upvotes: 3
Reputation: 3043
This one should work:
@url = 'http://fruits.com/A15/abc1234-apple-w740_h550_q58.jpg'
def last_part_of_url
fruit = ['apple','banana','grape','butter','honey'].detect { |f| @url.include?(f) }
@url.split(fruit).last if fruit
end
Upvotes: 1
Reputation: 4615
try this:
url = 'http://fruits.com/A15/abc1234-apple-w740_h550_q58.jpg'
['apple','banana','grape','butter','honey'].select { |f| url.include? f }
Upvotes: 2