在散列上啪嗒啪嗒 [英] Splat on a hash
问题描述
一个散列图将其转换为一个数组。
[* {foo: :bar}]#=> [[:foo,:bar]]
是否存在一些隐藏机制(如隐式类转换)一个内置的原始特性?
除了一个数组, nil
消失/改变与红宝石1.9下的splat运算符?
为此,它会发送 to_a
并期望 Array
作为结果。
class Foo
def to_a
[1,2,3]
结束
结束
a,b,c = * Foo.new
a#=> 1
如果对象没有响应 to_a
,那么没有效果,例如 [* 42] == [42]
许多内建类实现 to_a
。特别是:
Enumerable
)
Array
哈希
范围
IO
和 File
Enumerator
Enumerator :: Lazy
(Ruby 2.0)
Set
和 SortedSet
NilClass
MatchData
OpenStruct
Struct
时间
矩阵
和 Vector
所有这些都可以被打碎:
$ b $
match,group,next_group = *Hello,world.match(/(.*),(。*)/)
组#=> 你好
A splat on a hash converts it into an array.
[*{foo: :bar}] # => [[:foo, :bar]]
Is there some hidden mechanism (such as implicit class cast) going on here, or is it a built-in primitive feature?
Besides an array, are
nil
and hash the only things that disappear/change with the splat operator under Ruby 1.9?
A splat will attempt an explicit conversion of an object to an Array.
To do this, it will send to_a
and expect an Array
as a result.
class Foo
def to_a
[1,2,3]
end
end
a, b, c = *Foo.new
a # => 1
If the object does not respond to to_a
, then there is no effect, e.g. [*42] == [42]
Many builtin classes implement to_a
. In particular:
- (because they include
Enumerable
)Array
Hash
Range
IO
andFile
Enumerator
Enumerator::Lazy
(Ruby 2.0)Set
andSortedSet
- (additional classes)
NilClass
MatchData
OpenStruct
Struct
Time
Matrix
andVector
All these can thus be splatted:
match, group, next_group = *"Hello, world".match(/(.*), (.*)/)
group # => "Hello"
这篇关于在散列上啪嗒啪嗒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!