如何防止数组串联更改所涉及数组的值?
How do I prevent array concatenation from changing the values of the arrays involved?
我想创建一些数组值常量,但在尝试连接它们时似乎遇到了问题。
MALE_TOKENS = %w(m male)
#=> ["m", "male"]
FEMALE_TOKENS = %w(f w female)
#=> ["f", "w", "female"]
GENDER_TOKENS = MALE_TOKENS.concat FEMALE_TOKENS
#=> ["m", "male", "f", "w", "female"]
MALE_TOKENS
#=> ["m", "male", "f", "w", "female"]
请注意,在 concat
生成之后,MALE_TOKENS
现在包含 FEMALE_TOKENS
。我不要这个。
如何将物品分开?
Array#concat
改变接收者:
Appends the elements of +other_ary+s to self
.
要不更改 MALE_TOKENS
值,您可以使用 Array#+
:
GENDER_TOKENS = MALE_TOKENS + FEMALE_TOKENS
#=> ["m", "male", "f", "w", "female"]
MALE_TOKENS
#=> ["m", "male"]
FEMALE_TOKENS
#=> ["f", "w", "female"]
我想创建一些数组值常量,但在尝试连接它们时似乎遇到了问题。
MALE_TOKENS = %w(m male)
#=> ["m", "male"]
FEMALE_TOKENS = %w(f w female)
#=> ["f", "w", "female"]
GENDER_TOKENS = MALE_TOKENS.concat FEMALE_TOKENS
#=> ["m", "male", "f", "w", "female"]
MALE_TOKENS
#=> ["m", "male", "f", "w", "female"]
请注意,在 concat
生成之后,MALE_TOKENS
现在包含 FEMALE_TOKENS
。我不要这个。
如何将物品分开?
Array#concat
改变接收者:
Appends the elements of +other_ary+s to
self
.
要不更改 MALE_TOKENS
值,您可以使用 Array#+
:
GENDER_TOKENS = MALE_TOKENS + FEMALE_TOKENS
#=> ["m", "male", "f", "w", "female"]
MALE_TOKENS
#=> ["m", "male"]
FEMALE_TOKENS
#=> ["f", "w", "female"]