Does the method verify the correctness and run it in a conditional expression (if)?

  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

I am studying a Ruby programming tutorial. The method addcreates a new instance, then saves it to a file (using the method save). In the conditional, ifI am curious to see how it was called save, given that it was never called directly.

I know when you put a method in an if condition and do not use any operators (for example: =, ==, etc.), you check the "truth" of the return value of this operator. But doesn't the method put in a conditional expression? If not, how is the method called savefor the above example invoked ?

+4
source share
2 answers

, , if.

: nil false false, truthy.

+3

, , nil. :

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

, nil, method_which_needs_a_non_nil_parameter .

+1

Source: https://habr.com/ru/post/1660547/


All Articles