2017-06-16 42 views
-1

我是ruby的新手,想要了解如何传递与ruby中的键相对应的值。 我有一个散列rubylike如下─ruby​​如何通过哈希值传递值

instance1 
shutdown_port: 1234 
startup_port: 1678 
instance2 
shutdown_port: 2234 
startup_port: 2678 

我想通过shutdown_portstartup_port每个实例的方法,但不想混shutdown_port & startup_port值。

类似的,if keyname = shutdown_port,通过相应的值和if if keyname = startup_port,通过相应的值。

+0

“我在rubylike哈希” - 这看起来并不像红宝石哈希,在所有。 –

+0

其实我正在写一个厨师食谱,这就是我将通过我的.kitchen.yml。我需要为每个实例读取“shutdown_port”和“startup_port” – user6378152

+2

这也不是有效的yaml。即使是这样,你也应该让我们摆脱这个实现细节。最终你会将它解析为散列。发布有效的散列。 –

回答

0

Ruby实际上允许keyword argument as of Ruby 2,它将解析一个哈希。

在你的情况,你想要的东西一样(只要你使用正确YAML.parse(file)获得哈希值。):

# method takes keyword args 
def idk(startup_port:, shutdown_port:) 
    p "#{startup_port}, #{shutdown_port}" 
end 

# which you call like this: 
idk({ startup_port: '22', shutdown_port: '80' }) 
# or without explicit hash 
idk(startup_port: '22', shutdown_port: '80') 
相关问题