如何在 Ruby 中调用具有特定参数的方法

How To Invoke Method With Specific Parameters In Ruby

这里是示例代码,

def fun(a = "default", b = "default")
    puts "#{a} and #{b}"
end
fun("hello")

这里我只想为 b 传递值,而不是为 a 传递值(即输出将是默认值和你好)。

谁能帮我解决这个问题。

如果您使用 Ruby >= 2,您可以将其转换为使用 keyword arguments,如下所示:

def fun(a: "default", b: "default")
  puts "#{a} and #{b}"
end
fun(b: "hello")

这应该会产生预期的输出。

希望对您有所帮助!

祝你好运!

更新 - hash "approach"

 def fun(options = {})
   defaults = { a: "default", b: "default" }
   options = defaults.merge(options)
   puts "#{options[:a]} and #{options[:b]}"
 end
 fun(b: "hello")