Ruby a Clever Way to Execute a Function on a Condition

Ruby a clever way to execute a function on a condition

commands = {
1 => ->(p1,p2) {...},
2 => ->(p1,p2) {...},
3 => ->(p1,p2) {...},
}

commands[score].call(p1,p2)

Insert your code in place of the ...'s, and your parameters in place of p1,p2. This will create a hash called commands, from integer scores to anonymous functions (-> is short for lambda). Then you look up the appropriate function based on the score, and call it!

Apply a method if condition

No, there is no builtin method for this, but you can write it more concisely using expression modifiers:

value = value.to_i if value.is_a?(String)

Passing different parameter to a method call depending on a condition in Ruby

Just add the condition into value .

:email        => (type==1 ? registration.email_2 :  registration.email),

How do I call a method that is a hash value?

that code doesn't work. it executes a at the time it is added to the hash, not when it is retrieved from the hash (try it in irb).

It doesn't work in the class because there is no a method defined on the class (you eventually define a method a on the instance.

Try actually using lambdas like

{0 => lambda { puts "hello world" }} 

instead

Idiomatic Ruby - Execute a function until it returns a nil, collecting its values into a list

Funny how nobody suggested Enumerator and its take_while method, to me it seems just fit:

# example function that sometimes returns nil
def func
r = rand(5)
r == 0 ? nil : r
end

# wrap function call into lazy enumerator
enum = Enumerator.new{|y|
loop {
y << func()
}
}

# take from it until we bump into a nil
arr = enum.take_while{|elem|
!elem.nil?
}

p arr
#=>[3, 3, 2, 4, 1, 1]

How to execute multiple succeeding functions in 1 line in Ruby?

One easy way is to just parenthesize the statements:

ruby-1.9.1-p378 > 0.upto(5) do |n|
ruby-1.9.1-p378 > (puts n; break;) if n == 3
ruby-1.9.1-p378 ?> puts ">>#{n}<<"
ruby-1.9.1-p378 ?> end
>>0<<
>>1<<
>>2<<
3

If it's a bit much to put in parentheses, a begin-end will do the trick:

0.upto(5) do |n|
begin
puts "I found a matching n!"
puts n
puts "And if you multiply it by 10, it is #{10*n}"
break;
end if n == 3
puts "((#{n}))"
end

Output:


((0))
((1))
((2))
I found a matching n!
3
And if you multiply it by 10, it is 30

How to store a value in a conditional statement and call it in ruby

I would do something like this:

def myname(re_generate = false)
@_myname = SecureRandom.urlsafe_base64(6) if @name.nil? || re_generate
@_myname
end


Related Topics



Leave a reply



Submit