Setting variables with blocks in ruby

I often use PHP-like loops in Ruby, and it doesn't feel like it when the rest of the language is so neat. I end up with the code as follows:

conditions_string = ''

zips.each_with_index do |zip, i|

    conditions_string << ' OR ' if i > 0
    conditions_string << "npa = ?"

end

# Now I can do something with conditions string

It seems to me that I can do something like this

conditions_string = zips.each_with_index do |zip, i|

    << ' OR ' if i > 0
    << "npa = ?"

end

Is there an Inactive way to set a variable with a block in Ruby?

+2
source share
5 answers

It seems you are not accessing zipin your loop, so the following should work:

conditions_string = (['npa = ?'] * zips.length).join(' OR ')

If you need access to zip, you can use:

conditions_string = zips.collect {|zip| 'npa = ?'}.join(' OR ')
+1
source

The first thing I thought was:

a = %w{array of strings}             => ["array", "of", "strings"]
a.inject { |m,s| m + ' OR ' + s }    => "array OR of OR strings"

But this can only be done with

a.join ' OR '

, , , :

([' npa = ? '] * a.size).join 'OR'
+4

zip,

zips.map {|zip| "npa = ?" }.join(" OR ")

Enumerable # inject, .

+4

, Object#instance_eval, , Ruby DSL. self instance_eval :

:

x = ''
x.instance_eval do
    for word in %w(this is a list of words)
        self << word  # This means ``x << word''
    end
end
p x
# => "thisisalistofwords"

, Perl $_, .

+1

1.8.7+ each_with_object

"" DigitalRoss :

a = %w{hello my friend}  => ["hello", "my", "friend"]
a.each_with_object("") { |v, o| o << v << " NOT " }  => "hello NOT my NOT friend NOT"
0

Source: https://habr.com/ru/post/1725323/


All Articles