Today I Learned

Nested assignments inside array assignment in Ruby

In Ruby, an assignment returns its value.

> a = 1
=> 1

You can slightly abuse it to nest variable assignments inside an array assignment:

a = [
  b = 1,
  c = 2
]

> a
=> [1, 2]
> b
=> 1
> c
=> 2

You could even go a step further to nest variable assignments inside array assignments nested inside yet another array assignment - although it seems to be losing readability at this point:

a = [
  *b = [
    c = 1,
    d = 2
  ],
  *e = [
    f = 3,
    g = 4
  ]
]

> a
=> [1, 2, 3, 4]
> b
=> [1, 2]
> c
=> 1

This may be useful in tests, where you have multiple variables, which you need to use both individually and collectively, and you want to have descriptive variable names:

triggers = [
  trigger_with_conditions_fulfilled = create(:trigger),
  trigger_with_conditions_not_fulfilled = create(:trigger)
]

allow(trigger_with_conditions_fulfilled).to receive(:conditions_fulfilled?).and_return(true)
allow(trigger_with_conditions_not_fulfilled).to receive(:conditions_fulfilled?).and_return(false)

ExecuteTriggers.call(triggers)