Assign Subset of Variables a Common Value via Parallel Assignment

时间:2016-07-11 19:58:51

标签: arrays ruby parallel-assignment

Within Ruby, I've been searching for an elegant single-line statement to assign multiple variables (but not all) a common value returned from an array via method call.

The crux of the objective is to convert a two-line statement such as:

a, x = 1, 2
y = x

Into: a, x, y = 1, 2, 2 without hard-coding the repeated values. So a gets one value (1) while x and y both share a common value (2).

To extend the example into a use-case, let's say instead of directly assigning the values 1, 2, we assign our values via an array returned from a method call:

a, x = 7.divmod 5  # array [1,2] is unpacked via parallel assignment
y = x

This has the same result as the first code sample and we could replace the Integers with variables to make the assignment dynamic.

Can you recommend techniques to consolidate this assignment into a single line? Here are a couple options I've considered so far:

n = 7 # number
m = 5 # divided by

# Option 1) Store array via inline-variable assignment and append last
#           element to align values for the parallel assignment
a, x, y = (t = n.divmod(m)) << t[-1]

# Option 2) Use Array#values_at to repeat some elements
a, x, y = n.divmod(m).values_at 0,1,1

For those new to parallel assignment, this SO post covers standard usage.

1 个答案:

答案 0 :(得分:1)

另一个选择

a, x, y = 7.divmod(5).tap {|a| a << a[-1]}