相关疑难解决方法(0)

为什么|| 和/或在rails中表现不同?

可能重复:
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)

ruby ruby-on-rails

3
推荐指数
1
解决办法
5836
查看次数

rails中的"和"vs"&&"运算符

根据这个堆栈问题,

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

任何人都可以解释为什么会发生这种情况.

ruby ruby-on-rails

2
推荐指数
1
解决办法
982
查看次数

RuboCop-为整个Rails项目禁用Style / AndOr?

我正在和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完全禁用它,我更喜欢它。这可能吗,如果可以,我将如何去做?

ruby rubocop

1
推荐指数
1
解决办法
32
查看次数

带有函数的 Ruby 迭代器。返回函数的第一个值而不迭代整个列表

我有一个数组: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)

ruby

1
推荐指数
1
解决办法
166
查看次数

Ruby逻辑运算符

可能重复:
Ruby中的"和","或"运算符背后有智慧吗?

以下逻辑运算符对之间有什么区别?

  1. && vs.和
  2. || vs.或

ruby logical-operators

0
推荐指数
1
解决办法
4577
查看次数

标签 统计

ruby ×5

ruby-on-rails ×2

logical-operators ×1

rubocop ×1