开发者

how to write a block that returns a string in ruby

开发者 https://www.devze.com 2022-12-10 04:52 出处:网络
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:

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消