Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform variable assignment with a loop, and break?

Tags:

ruby

Here is the logic:

y = 'var to check for'

some_var = some_loop.each do |x|
  x if x == y
  break if x
end

Is there a better way to write this?

Something like

x && break if x == y

Thank you in advance!

like image 238
fr00z1 Avatar asked Dec 11 '25 01:12

fr00z1


2 Answers

The correct answer is to use include?. eg:

found = (array_expression).include? {|x| x == search_value}

It's possible to also use each and break out on the first matched value, but the C implementation of include? is faster than a ruby script with each.

Here is a test program, comparing the performance of invoking include? on a very large array vs. invoking each on the same array with the same argument.

#!/usr/bin/env ruby
#
require 'benchmark'

def f_include a, b
  b if a.include?(b)
end

def f_each_break a, b
  a.each {|x| return b if x == b }
  nil
end

# gen large array of random numbers
a = (1..100000).map{|x| rand 1000000}

# now select 1000 random numbers in the set
nums = (1..1000).map{|x| a[rand a.size]}

# now, check the time for f1 vs. f2
r1 = r2 = nil

Benchmark.bm do |bm|
  bm.report('incl') { r1 = nums.map {|n| f_include    a,n} }
  bm.report('each') { r2 = nums.map {|n| f_each_break a,n} }
end
if r1.size != r2.size || r1 != r2
  puts "results differ"
  puts "r1.size = #{r1.size}"
  puts "r2.size = #{r2.size}"
  exceptions = (0..r1.size).select {|x| x if r1[x] != r2[x]}.compact
  puts "There were #{exceptions.size} exceptions"
else
  puts "results ok"
end

exit

Here is the output from the test:

$ ./test-find.rb
       user     system      total        real
incl  5.150000   0.090000   5.240000 (  7.410580)
each  7.400000   0.140000   7.540000 (  9.269962)
results ok
like image 107
aks Avatar answered Dec 13 '25 14:12

aks


Why not:

some_var = (some_loop.include? y ? y : nil)
like image 33
Adrian Avatar answered Dec 13 '25 15:12

Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!