简体   繁体   English

是否可以使用do块初始化Ruby哈希?

[英]Is it possible to initialize a Ruby hash with a do block?

I love the feel of the Ruby do ... end block, and I would love to be able to use it to initialize a hash. 我喜欢Ruby do ... end块的感觉,并且我希望能够使用它来初始化哈希。 I'm aware of the curly brace construction, eg 我知道花括号的构造,例如

h = {
  :a => 10,
  :b => 20
}

But I was wondering if there's a way to do the same sort of thing with a do block, eg 但是我想知道是否有办法用do块做同样的事情,例如

h_keys = keys do
  :a => 10,
  :b => 20
end

Edit 编辑

Let me be clearer: I do understand that a hash literal is not a block, and I have a pretty good grasp of the internals of a block. 让我更清楚一点:我确实理解哈希文字不是一个块,并且我对块的内部有了很好的了解。 What I'm wondering is more along the lines of this: 我想知道的更多是这样的:

Is it possible, perhaps via (but not constrained to) some clever metaprogramming method, to write a function such that a block passed into it is interpreted as a hash? 是否有可能通过(但不限于)某种聪明的元编程方法来编写一个函数,以便将传递给它的块解释为哈希?

This is a bit similar to your desired sample code, though the do ... end is gone: 尽管do ... end了,但这有点类似于您所需的示例代码:

 def keys(x); x; end
 h = keys a: 1, b: 2

Unfortunately keys do a: 1, b: 2 end doesn't match Ruby's grammar. 不幸的是, keys do a: 1, b: 2 end与Ruby的语法不匹配。 Naturally, you could still write a preprocessor which would run over a source file, rewrite your added syntax to standard Ruby syntax, then feed it to the interpreter. 当然,您仍然可以编写一个可以在源文件上运行的预处理器,将添加的语法重写为标准Ruby语法,然后将其提供给解释器。 That would be more than a little crazy, but if you want to do it, more power to you... 那会有点疯狂,但是如果您想这样做,就会为您带来更大的力量...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM