可能重复:
Ruby中的i = true和false是真的吗?
Perl(或,和)和(||,&&)短路运营商之间有什么区别?
Ruby:||之间的区别 和'或'
是||一样or的Rails的?
案例A:
@year = params[:year] || Time.now.year
Events.all(:conditions => ['year = ?', @year])
Run Code Online (Sandbox Code Playgroud)
将产生以下SQL script/console:
SELECT * FROM `events` WHERE (year = 2000)
Run Code Online (Sandbox Code Playgroud)
案例B:
@year = params[:year] or Time.now.year
Events.all(:conditions => ['year = ?', @year])
Run Code Online (Sandbox Code Playgroud)
将产生以下SQL script/console:
SELECT * FROM `events` WHERE (year = NULL)
Run Code Online (Sandbox Code Playgroud) 根据这个堆栈问题,
and是相同&&但优先级较低
而且我理解这一点.我相信这个问题与上述问题不重复.
在我的控制器中执行以下代码时:
user = user_email.present? && User.find_by(email: user_email)
user变量保存active record objectfor Usermodel.因此执行user.valid_password? user_password没有错误,测试成功通过.
但是当我试图&&用and结果取代时却相当令人惊讶.
当我尝试使用以下代码时:
user = user_email.present? and User.find_by(email: user_email)
user变量保存boolean值,因此执行user.valid_password? user_password给出以下错误:
未定义的方法`valid_password?' 为true:TrueClass
任何人都可以解释为什么会发生这种情况.
我正在和Rubocop玩耍,有一些约定我比标准Rubocop遵循。考虑以下:
if some_variable and another
do_this
end
Run Code Online (Sandbox Code Playgroud)
Rubocop抱怨我应该使用&&而不是and这里。我检查了文件和默认设置Style/AndOr就是always。但是,它确实具有设置(conditionals),允许我执行以下操作:
model.save! and return
Run Code Online (Sandbox Code Playgroud)
...但是我只想为我的Rails项目完全关闭此标准。Rubocop确实让我对每个实例执行以下操作:
# rubocop:disable Style/AndOr
if check_this and check_that
# rubocop:enable Style/AndOr
do_something
end
Run Code Online (Sandbox Code Playgroud)
...但是那似乎真的很乏味,所以如果我可以Style/AndOr完全禁用它,我更喜欢它。这可能吗,如果可以,我将如何去做?
我有一个数组:arr=[x1, x2, x3...]和一个函数,该函数基于第一个函数返回一个值x,因为arr该函数是真实的。
本质上:
# my_x is the return of func()
# with the first x in arr that func(x) is true
# and the entire arr array is not processed.
my_x=arr.ruby_magic{|x| func(x) }
my_x should be equal to first true value return of func(x)
Run Code Online (Sandbox Code Playgroud)
假设每个Xinarr都是一个正则表达式模式。无需运行每个正则表达式,我想返回第一场比赛的捕获组。
在 Python 中,我会用next. 它将运行每个谓词,直到返回真值,然后将该值传递给m。如果没有 true return,None则用作默认值,但该默认值可以是任何值:
import re
patterns=[r"no match", r": (Value.*?pref)", r": (Value.*)", r"etc..."]
s="""
This is …Run Code Online (Sandbox Code Playgroud)