Dav*_*ows 169 ruby operators splat
鉴于Ruby代码
line = "first_name=mickey;last_name=mouse;country=usa"
record = Hash[*line.split(/=|;/)]
Run Code Online (Sandbox Code Playgroud)
除了*
操作员之外,我理解第二行中的所有内容 - 它在做什么以及文档在哪里?(正如你可能猜到的那样,寻找这个案子很难......)
mol*_*olf 262
这*
是splat运算符.
它将一个Array
参数列表扩展为一个参数列表,在本例中是一个参数列表Hash.[]
.(更准确地说,它扩展了响应to_ary
/ to_a
或to_a
Ruby 1.9中的任何对象.)
为了说明,以下两个陈述是相同的:
method arg1, arg2, arg3
method *[arg1, arg2, arg3]
Run Code Online (Sandbox Code Playgroud)
它也可以在不同的上下文中使用,以捕获方法定义中的所有剩余方法参数.在这种情况下,它不会扩展,但结合:
def method2(*args) # args will hold Array of all arguments
end
Run Code Online (Sandbox Code Playgroud)
BJ *_*mer 43
splat运算符解包传递给函数的数组,以便将每个元素作为单个参数发送到函数.
一个简单的例子:
>> def func(a, b, c)
>> puts a, b, c
>> end
=> nil
>> func(1, 2, 3) #we can call func with three parameters
1
2
3
=> nil
>> list = [1, 2, 3]
=> [1, 2, 3]
>> func(list) #We CAN'T call func with an array, even though it has three objects
ArgumentError: wrong number of arguments (1 for 3)
from (irb):12:in 'func'
from (irb):12
>> func(*list) #But we CAN call func with an unpacked array.
1
2
3
=> nil
Run Code Online (Sandbox Code Playgroud)
而已!
正如大家所说,这是一个"啪啪".寻找Ruby语法是不可能的,我在其他问题中也问过这个问题.这部分问题的答案是你搜索
asterisk in ruby syntax
Run Code Online (Sandbox Code Playgroud)
在谷歌.谷歌就是为你而存在的,只要把你所看到的东西放进去.
Anyhoo,就像许多Ruby代码一样,代码非常密集.该
line.split(/=|;/)
Run Code Online (Sandbox Code Playgroud)
制作一个SIX元素数组first_name, mickey, last_name, mouse, country, usa
.然后使用splat将其变成哈希.现在Ruby人总是会发送给你看看Splat方法,因为所有内容都在Ruby中公开.我不知道它在哪里,但是一旦你有了它,你会看到它for
通过数组运行并构建哈希.
您将在核心文档中查找代码.如果你找不到它(我不能),你会尝试写一些像这样的代码(它可以工作,但不是类似Ruby的代码):
line = "first_name=mickey;last_name=mouse;country=usa"
presplat = line.split(/=|;/)
splat = Hash.new
for i in (0..presplat.length-1)
splat[presplat[i]] = presplat[i+1] if i%2==0
end
puts splat["first_name"]
Run Code Online (Sandbox Code Playgroud)
然后Ruby团队将能够告诉你为什么你的代码是愚蠢的,坏的,或者只是完全错误.
如果您已经阅读过这篇文章,请阅读Hash文档以进行初始化.
基本上,使用多个参数初始化的哈希将它们创建为键值对:
Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
Run Code Online (Sandbox Code Playgroud)
因此,在您的示例中,这将导致以下Hash:
{"first_name"=>"mickey", "last_name"=>"mouse", "county"=>"usa"}
Run Code Online (Sandbox Code Playgroud)