是否可以在 Ruby 方法中使用哈希键作为第一级变量



我会试着多解释一下自己

# Lets say I have this hash
options = {a: 1, b: 2}
# and here I'm calling the method
some_method(options)
def some_method(options)
  # now instead of using options[:a] I'd like to simply use a.
  options.delete_nesting_and_create_vars
  a + b # :a + :b also good.

谢谢!

是否可以使用 Ruby2 splat 参数:

options = {a: 1, b: 2}
def some_method1(a:, b:)
  a + b
end

或:

def some_method2(**options)
  options[:a] + options[:b]
end

some_method1 **options
#⇒ 3
some_method2 **options
#⇒ 3

如果你的选项是固定的,比如只有:a:b是唯一的键,你可以像这样编写方法:

def some_method(a:, b:)
  a + b
end
options = {a: 1, b: 2}
some_method(options) #=> 3

最新更新