Ruby has something similar to. =, Like + =?

So how can you do:

a += 1

I was thinking if it is possible to do something similar to:

a .= 1

An example of use will be, for example, using ActiveRecord:

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

Is it possible somehow?

+4
source share
2 answers

No, Ruby has nothing of the kind. Only certain "compound statements" are allowed by Ruby syntax, and this statement is not one of them.

However, under certain circumstances there may be workarounds (but not this one). If, say, you had an array, then instead

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

you could do

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

(This can have unintended consequences, yes, because an internal mutation is generally dangerous, but in some cases it is desirable. Do not do this to shorten your code.)

+6
source

Ruby :

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

( ):

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

, - , IRB, ( ) , . IRB , . Ruby script .

, , .

, , . , . , :

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

, , . , .

+6

Source: https://habr.com/ru/post/1676782/


All Articles