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
LINQ in Ruby?
So this is what was given
class BirdCount
def self.last_week
[0, 2, 5, 3, 7, 8, 4]
end
def initialize(birds_per_day)
@birds_per_day = birds_per_day
end
def yesterday
@birds_per_day[-2]
end
def total
@birds_per_day.sum
end
def busy_days
@birds_per_day.count { |day| day >= 5 }
end
def day_without_birds?
@birds_per_day.any? { |day| day == 0 }
end
end
Which looks canna complicated but really it just like this in C#
public class BirdCount
{
public int[] BirdsPerDay { get; }
public BirdCount(int[] birdsPerDay)
{
BirdsPerDay = birdsPerDay;
}
}
var birds = new BirdCount(new[] { 0, 2, 5, 3, 7, 8, 4 });
birds.Where(day => day >= 5).Count();