Dan*_*ton 33 ruby boolean variable-assignment
可能重复:
Ruby中的|| =是什么意思?
请原谅我,如果这是一个新问题,但我正在读一本关于作者在辅助方法中使用此表达式的轨道上的书:
@current_user ||= User.find_by_id(session[:user_id])
Run Code Online (Sandbox Code Playgroud)
这种双管道的使用仍然是一个布尔OR语句吗?
如果是这样,它是如何工作的?
Kla*_*sen 58
这是一个有条件的任务.从这里:
x = find_something() #=>nil
x ||= "default" #=>"default" : value of x will be replaced with "default", but only if x is nil or false
x ||= "other" #=>"default" : value of x is not replaced if it already is other than nil or false
Run Code Online (Sandbox Code Playgroud)
Phr*_*ogz 18
代码foo ||= bar几乎相当于foo = foo || bar.在Ruby中(如在许多语言中,如JavaScript或Io),布尔运算符是"保护"运算符.而不是总是返回true或者false,它们评估为第一个操作数的值,该操作数的值是"truthy"值.
例如,此代码foo = 1 || delete_all_files_from_my_computer()不会删除任何内容:foo将被设置为1,第二个操作数甚至不会被评估.
在Ruby中,唯一的"非真实"值是nil和false.所以代码foo ||= bar只会评估bar并设置foo为结果,如果foo是nil或false.
由于实例变量默认为nil未设置,因此代码类似于@foo ||= bar设置实例变量的常用Ruby习惯用法(如果尚未设置).
您可以将其视为简称:
@current_user = @current_user || User.find_by_id(session[:user_id])
Run Code Online (Sandbox Code Playgroud)
@current_user 首先进行评估,如果它是非null,则OR返回@ current_user的值,并且不调用User.find_by_id.