pol*_*lau 19 ruby hash reference
是否可以在同一哈希中的另一个元素中引用哈希中的一个元素?
# Pseudo code
foo = { :world => "World", :hello => "Hello #{foo[:world]}" }
foo[:hello] # => "Hello World"
Run Code Online (Sandbox Code Playgroud)
Dig*_*oss 14
间接地也许......
foo = { :world => 'World', :hello => lambda { "Hello #{foo[:world]}" }}
puts foo[:hello].call
Run Code Online (Sandbox Code Playgroud)
如果您想使某些键的值依赖于其他键:
foo = Hash.new{|h, k|
case k
when :hello; "Hello #{h[:world]}"
when :bye; "Bye #{h[:world]}"
end
}
foo[:world] = 'World'
foo[:hello] # => 'Hello World'
foo[:bye] # => 'Bye World'
foo[:world] = 'Heaven'
foo[:hello] # => 'Hello Heaven'
foo[:bye] # => 'Bye Heaven'
Run Code Online (Sandbox Code Playgroud)