如果传递"1"/"0"或"true"/"false",写一个函数返回"true"或"false"

far*_*any -2 ruby

我需要一个简单的函数来返回"true"或"false"传递给它的参数是:

1或者0,true或者false

我目前有这样的事情,所以答案,如果可能的话,应该简洁如下:

def boolean(value); return value ? ( value == 1 ? "true" : "false) : nil; end
Run Code Online (Sandbox Code Playgroud)

谢谢.

Aug*_*ust 5

一些想法:

def boolean(x)
   %w{1 true}.include?(x).to_s
end
Run Code Online (Sandbox Code Playgroud)
def boolean(x)
  (x == '1' || x == 'true').to_s
end
Run Code Online (Sandbox Code Playgroud)

还有崇拜宝石的宝石:

require 'wannabe_bool'

'1'.to_b # => true
'0'.to_b # => false

'true'.to_b  # => true
'false'.to_b # => false
Run Code Online (Sandbox Code Playgroud)