how to write a block that returns a string in ruby
A function takes a string as argument, example fn("string").
I want to pass different values depending on three of more conditions, and one approach which is slightly unreadable is:
fn(check_1 ? "yes" : check_2 ? "no" : "maybe")
I want to replace the argument with a block that returns a string. i am hoping i can do something like:
fn({|arg| if check_1
arg = "yes"
elsif check_2
arg = "no"
else
arg = "maybe"
end
})
I can have more conditions and would still be able to write all this as if this was in one line.
开发者_开发百科How do I do this in Ruby?
Block is cool ,but it doesn't mean we always have to use it.
IMHO , It would be much more clear to use a seperated function to get the string you want to pass to the fn
.
def arg w
if w.eql? "check_1"
"yes"
elsif w.eql? "check_2"
"no"
else
"maybe"
end
end
def fn s
puts s
end
fn(arg("check_1"))
fn(arg("check_2"))
fn(arg("check_3"))
Or use a Hash
,which is left to you as an exercise :)
This sounds a little strange. Are you sure you don't want to pass in an array and process the arguments from within the method?
either way, it kind of sounds like you what you are asking for is a lambda to process the logic, and then you can pass the lambda into the function to return the actual results.
def test(parameter)
puts "I was passed the value: #{parameter}"
end
foo = lambda{|x,y,z|
if x == true
"yes"
elsif y == true
"no"
else
"maybe"
end
}
test(foo[false,true,false])
You can use an if
expression, or even a case
expression. See the PickAxe book. An example of what you want to do is all the way at the top of the page.
arg= check_1&&"yes"||check_2&&"no"||"maybe"
It seems you have some misconceptions about blocks, but it's another matter entirelly.
I think that will help you:
check_1 = false
check_2 = true
def foo(&block)
puts block.call
end
foo {
if check_1
arg = "yes"
elsif check_2
arg = "no"
else
arg = "maybe"
end
}
精彩评论