简体   繁体   English

Ruby有类似于。=,类似+ =?

[英]Does Ruby have something similar to .=, like +=?

Since one can do: 既然可以这样做:

a += 1

I was thinking whether one can also do something similar to: 我在想是否也可以做类似的事情:

a .= 1

The use case would be, for example, with ActiveRecord: 例如,用例将与ActiveRecord一起使用:

query = Model
query .= where(name: 'John') # instead of query = query.where(name: 'John')

Is this possible somehow? 这有可能吗?

Nope, ruby does not have anything like this. 不,红宝石没有这样的东西。 Only certain "compound operators" are allowed by Ruby syntax and this operator is not among them. Ruby语法只允许某些“复合运算符”,并且此运算符不在其中。

However, there might be workarounds under specific circumstances (not this one, though). 但是,在特定情况下可能会有解决方法(不过这一点)。 If, say, you had an array, then instead of 比方说,如果你有一个数组,那么而不是

ary = ary.select { ... } if foo
ary = ary.select { ... } if bar
ary = ary.compact

you'd be able to do 你能做到的

ary.select! { ... } if foo
ary.select! { ... } if bar
ary.compact!

( this can have unintended consequences, yes, because in-place mutation is dangerous in general. But in some cases it is desirable. Don't do it to shorten your code. ) 这可能会产生意想不到的后果,是的,因为就地变异通常是危险的。但在某些情况下这是可取的。不要这样做以缩短你的代码。

Ruby is able to detect line continuations automatically: Ruby能够自动检测行延续:

query = Model
  .where(name: 'John')
  .select(:first_name)

This is equivalent to this (with the dots at the end): 这相当于此(末尾有点):

query = Model.
  where(name: 'John').
  select(:first_name)

Note that due to the way lines are evaluated in IRB, only the second syntax (with the dots at the end of the line) works as intended there. 请注意,由于在IRB中评估行的方式,只有第二种语法(行末尾的点)按预期工作。 With the first example, IRB would evaluate the line as soon as it sees the newline. 在第一个例子中,IRB会在看到换行符后立即对该行进行评估。 In a Ruby script, both options work quite well. 在Ruby脚本中,两个选项都运行良好。

There apply different style considerations here, with people having different opinions on which one is best. 这里应用了不同的风格考虑因素,人们对哪一个最好有不同的看法。

Generally, this approach requires that the combined line is syntactically equivalent to a single line. 通常,这种方法要求组合线在语法上等同于单条线。 You can't use inline conditions that way. 您不能以这种方式使用内联条件。 This would thus be invalid syntax: 因此这将是无效的语法:

query = Model
  .where(name: 'John') if some_condition
  .select(:first_name)

If you require these conditions, it is just fine to assign intermediate results to a local variable as shown by Sergio Tulentsev in his answer. 如果您需要这些条件,可以将中间结果分配给局部变量,如Sergio Tulentsev在其答案中所示。 You'll often see this and it is not a code smell at all. 你会经常看到它,它根本不是代码味道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM