Ruby Training
Introduction
This is to summarised what I learn on the ruby Training
Returning if true
Quite liked this. On do the return if true
def remaining_minutes_in_oven(actual_minutes_in_oven)
return EXPECTED_MINUTES_IN_OVEN - actual_minutes_in_oven if actual_minutes_in_oven < EXPECTED_MINUTES_IN_OVEN
raise 'Please implement the Lasagna#remaining_minutes_in_oven method'
end
Symbols
Symbols are just an identifier
class User
STATES = [:active, :inactive, :banned]
...
Provide you pass the same thing, they are the same thing e.g.
User.new(:active)
Predicate Method
So in ruby you have a predicate method of a method that returns true or false which is, by convention, not enforced, a method with a ?. The example below returns true if status equal true.
class User
STATES = [:active, :inactive, :banned]
def initialize(status)
raise "Invalid state" unless STATES.include?(status)
@status = status
end
def active?
@status == :active
end
end
This became a bit more obvious the usage with the example with ranges
module Chess
RANKS = 1..8
FILES = 'A'..'H'
def self.valid_square?(rank, file)
RANKS.include?(rank) && FILES.include?(file)
end
end
Interpolation
This is how to interpolation works
my_var1 = "HELLO"
my_var2 = "FRED WAS HERE #{my_var1}"
puts my_var2