the12 the12 - 21 days ago 8
Ruby Question

Does checking the truthiness of a method also run it in a conditional statement (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 learning from a tutorial how to code in Ruby. The method
add
creates a new instance, then saves it to a file (using method
save
). In the conditional
if
, I am curious to see how
save
was invoked, considering that it was never directly called.

I know when you put a method within the if conditional and don't use any operators (i.e.: =,==,etc.) you are checking for the "truthiness" of the return value of that statement. But does putting a method in a conditional also run it? If not, how does the method
save
get called for the above example?

Answer

Sure, that method is called, executed and its return value is used as your if condition.

Just to recap: only nil and false are falsey value, anything other value is considered true.

Comments