2016-10-11 76 views
1

我想使用多个赋值,但我不关心输入中的某些部分值。那么有没有办法将一些东西分配给void变量(bash中的/dev/null)?类似nil = 'I wont be used'。我有一个更具体的例子来说明我想要达到的目标。如何使用ruby的多重赋值将值赋给void变量?

我输入的是:

['no','foo','nop','not at all','bar'] 

而且我给你这样说:

i,foo,dont,care,bar = ['no','foo','nop','not at all','bar'] 
#or with a splat : 
dont,foo,*care,bar = ['no','foo','nop','not at all','bar'] 

我想什么做的是这样的:

nil,foo,*nil,bar = ['no','foo','nop','not at all','bar'] 
+0

一种常见方法是只使用'_'作为占位符变量。 – halfelf

回答

3
_, foo, *_, bar = ['no','foo','nop','not at all','bar'] 
foo #=> "foo" 
bar #=> "bar" 
_ #=> ["nop", "not at all"] 

您也可以用*_替换只是*

是的,_是一个完全有效的局部变量。

当然,您不必使用_作为您不会使用的值。例如,你可以写

cat, foo, *dog, bar = ['no','foo','nop','not at all','bar'] 

使用_可减少错误的机会,但主要是告诉你不打算使用该值的读者。有些人喜欢使用可变名称以下划线开始对值将不被使用:

_key, value = [1, 2] 

如果分配较少的变量存在的阵列的元件,在阵列端部的元件将被丢弃。例如,

a, b = [1, 2, 3] 
a #=> 1 
b #=> 2 
+0

我的建议是玩弄不同的表情来看看你得到了什么。基本规则是,如果可以断定只有一个赋值给变量,那就没关系。 '* a,b,* c = [1,2,3,4,5]'是一个赋值不明确的例子,导致Ruby引发一个异常。 –

+0

我的linter删除了_unused variable_标志,如果我写'_'或者即使我写了'_some_random_name',是否有关于它的约定? –

+0

@UlysseBN,我没有关注“linter”,但是,是的,有些人写了'_unused_key'。我编辑了我的回答,提到这一点。谢谢。 –

1

也可以使用values_at提取从阵列的某些元素:

ary = ['no','foo','nop','not at all','bar'] 

foo, bar = ary.values_at(1, -1) 

foo #=> "foo" 
bar #=> "bar" 

此外指数,它也可以接受的范围:

ary.values_at(0, 2..3) #=> ["no", "nop", "not at all"]