Ruby lazy if语句没有运算符

Aks*_*hat 3 ruby ruby-on-rails

是否有可能在红宝石中这样做?

variablename = true
if variablename
   puts "yes!"
end
Run Code Online (Sandbox Code Playgroud)

而不是这个

variablename = true
if variablename == true
   puts "yes!"
end
Run Code Online (Sandbox Code Playgroud)

编辑:还考虑:

variablename = 0 #which caused my problem
Run Code Online (Sandbox Code Playgroud)

我无法让它发挥作用.如果可能的话,这样的风格是什么?我现在正在学习ruby,它可以在PHP中使用,但我不确定如何在ruby中正确执行

Vla*_*ich 9

当然,这是可能的

除了一切nil,并false在红宝石视为真.含义:

var = 0
if var
  # true!
end

var = ''
if var
  # true!
end

var = nil
if var
  # false
end
Run Code Online (Sandbox Code Playgroud)

  • 它不被视为"true"而只是*truthy*,所以只有在查询trutyiness的语句中(例如`if`或`case`)它才是等价的.但是,如果你将真实的价值与"真实"进行比较,你仍然会得到不平等. (3认同)