Reputation: 1333
Can you show me the way to get content my device
and image
in this string by ruby
if(my_device=='galaxytab210') { image = 'http:image.com'
Thank you so much!
Upvotes: 0
Views: 104
Reputation: 700
Interestingly, benchmarking some code reveals some very minor efficiencies in using a lookaround instead of the capture group and Array#flatten.
EDIT NOTE: Fixed the code as Arie pointed out and the capture + flatten method appears to be more efficient. This might be due to the speed of Array operations, which are analogous to the C code (and therefore more simply modeled) they are written in in MRI ruby.
#!/usr/bin/env ruby
require 'benchmark'
str = "if(my_device=='galaxytab210') { image = 'http:image.com'"
def with_lookaround(str)
str.scan(/(?<=')[^'\s]+(?=')/)
end
def with_flatten(str)
str.scan(/'([^']+)'/).flatten
end
repetitions = 1_000_000
Benchmark.bm do |bm|
bm.report('with lookaround') { repetitions.times { with_lookaround(str) } }
bm.report('with array flatten') { repetitions.times { with_flatten(str) } }
end
__END__
user system total real
with lookaround 5.140000 0.020000 5.160000 ( 5.181926)
with array flatten 4.950000 0.020000 4.970000 ( 5.041639)
user system total real
with lookaround 5.200000 0.020000 5.220000 ( 5.281581)
with array flatten 4.680000 0.020000 4.700000 ( 4.755978)
Upvotes: 1
Reputation: 14082
str = %q|if(my_device=='galaxytab210') { image = 'http:image.com'|
my_device, image = str.scan(/'([^']+)'/).flatten
Upvotes: 1