【问题标题】:Does checking the truthiness of a method also run it in a conditional statement (if)?检查方法的真实性是否也在条件语句(如果)中运行?
【发布时间】:2016-11-11 21:07:28
【问题描述】:
  def add
    puts "\nAdd a restaurant\n\n".upcase
    restaurant = Restaurant.new

    print "Restaurant name: "
    restaurant.name = gets.chomp.strip

    if restaurant.save
      puts "\nRestaurant Added\n\n"
    else
      puts "\nSave Error: Restaurant not added\n\n"
    end
  end

  def save
    return false unless Restaurant.file_usable?
    File.open(@@filepath, 'a') do |file|
      file.puts "#{[@name, @cuisine, @price].join("\t")}\n"
    end
    return true
  end

我正在学习如何使用 Ruby 编写代码的教程。方法add 创建一个新实例,然后将其保存到文件中(使用方法save)。在有条件的if 中,我很想知道save 是如何被调用的,因为它从未被直接调用过。

我知道当您在 if 条件中放置一个方法并且不使用任何运算符(即:=、== 等)时,您正在检查该语句的返回值的“真实性”。但是将方法放入条件中也会运行它吗?如果没有,上面的例子如何调用save 方法?

【问题讨论】:

  • 如果不调用该方法,if 语句将如何评估其条件的真实性?

标签: ruby methods


【解决方案1】:

当然,该方法已被调用、执行,其返回值用作您的 if 条件。

回顾一下:只有nilfalse 是虚假值,其他任何值都被认为是truthy

【讨论】:

    【解决方案2】:

    请注意,有时您需要评估会引发带有 nil 参数的异常的方法的真实性。 避免异常的一种可能性是:

    if !parameter.nil? && method_which_needs_a_non_nil_parameter(parameter) then
      do_something
    end
    

    在这种情况下,如果参数为 nil,则根本不会调用 method_which_needs_a_non_nil_parameter

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 1970-01-01
      相关资源
      最近更新 更多