【问题标题】:How to pass an optional method parameter as string in Ruby如何在Ruby中将可选方法参数作为字符串传递
【发布时间】:2019-09-06 08:07:46
【问题描述】:

我想在 Ruby 中调用一个方法,它有一个可选参数。

我尝试了一些方法,但都没有奏效。 你能帮我吗,我该如何调用这个方法? 我以前从未使用过 Ruby,所以请帮我完善问题本身。我试图用谷歌搜索这个问题,但我认为我使用了错误的术语。

我读到这个:Ruby Methods and Optional parameters 和这个:A method with an optional parameter,但没有运气。

方法如下:

def method(param1, param2, options={})

    ...

    if options["something"]
        ...
    end

    ...

end

我尝试了调用,例如,像这样:

method("param1", "param2", :something => true)

通过我的尝试,代码已运行,但未进入if 条件。 我想调用这个方法,这样if语句中的代码就会被运行。

【问题讨论】:

  • :something != "something"。一个是Symbol,另一个是String

标签: ruby parameter-passing


【解决方案1】:

它不起作用,因为您发送的是 symbol (:something) 而不是 string 密钥 ('something')。它们是不同的对象。

变化:

method("param1", "param2", :something => true)

method("param1", "param2", 'something' => true)

或通过if options[:something]处理方法

【讨论】:

  • 对我自己来说不是:"something" 不起作用。只需'something'
【解决方案2】:

使用相同的参数类型调用您的方法,或者如果您希望能够传递符号或字符串键,您可以在您的方法中处理它。

def foo(a,b, opt={})
  if opt[:something] || opt['something']
    puts 'something'
  end
end

现在您可以使用字符串或符号键调用它:

foo('a','b', 'something' => true )
#or 
foo('a','b', something: true )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2010-10-06
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多