【问题标题】:How to access method return from if statement in Ruby?如何从 Ruby 中的 if 语句访问方法返回?
【发布时间】:2017-03-19 23:10:18
【问题描述】:

我有一个返回数组的方法,如下所示:

def foobar(foo, bar)
  if foo != bar
    [foo, bar]
  end
end

现在,我想使用 if 语句从我的代码中调用此方法。如何在不复制方法的情况下访问数组值?

if foobar("baz", "qux")
    foo = foobar("baz", "qux")
    puts foo[0], foo[1]
end

为了进一步澄清,当您在 if 语句中调用正则表达式匹配时,我的意思类似于 $~。

【问题讨论】:

    标签: ruby if-statement methods return


    【解决方案1】:

    Ruby 有一个叫做“局部变量”的概念。您可以将对象分配给变量,然后引用这些变量:

    if foo = foobar('baz', 'qux')
      puts foo[0], foo[1]
    end
    

    请注意 Kernel#puts 特殊情况 Array 参数并在新行上打印它们的元素,因此您的代码相当于更惯用的代码

    if foo = foobar('baz', 'qux')
      puts foo
    end
    

    【讨论】:

    • 不错!正是我需要的,但无法弄清楚。谢谢!我也意识到第二部分,但这真的不是我的重点,因为我的实际代码与这个简化版本有很大的不同。
    • @MattSchuchard:我到底应该根据什么来测试相等性? OP 的代码中没有相等性测试。
    猜你喜欢
    • 2011-12-01
    • 2020-02-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-07-27
    • 2010-12-05
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多