Ruby/Statement/BEGIN END

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Execution Before or After a Program

# BEGIN and END code to execute before and after a program runs. 
# Both BEGIN and END are followed by blocks enclosed by braces ({})
BEGIN { puts "Date and time: " + Time.now.to_s }
def bmi( weight, height )
  703.0*( weight.to_f/(height.to_f**2))
end
my_bmi = bmi( 196, 73 )
puts "Your BMI is: " + x = sprintf( "%0.2f", my_bmi )
END { puts "You"ve got some work ahead of you." }



The code in a block labeled END is automatically run when the program finishes.

BEGIN {puts "Hi "}
puts "there "
END {puts "sweetie."}



The code in a block labeled with the keyword BEGIN is run automatically when a Ruby program is loaded

BEGIN {puts "Hi "}
puts "there "
END {puts "sweetie."}