A great ruby kata that demonstrates, and helps you understand how to extend the functionality of built-in ruby classes.
Problem Statement: Test your ability to extend built-in classes by adding the methods square(), sum(), average(), cube(), even(), and odd() to the Array class. These methods return a copy of the original array, after execution.
This is a great kata to learn and understand how classes, modules, and methods can be extended in Ruby.
Test Cases & Kata.
Ruby Kata: Extending The Built-In Ruby Classes.
Here’s How I Solved It
class Array
def square
self.map{ |x| x**2 }
end
def cube
self.map{ |x| x**3 }
end
def sum
inject(0) { |result, el| result + el }
end
def average
self.sum / self.size
end
def even
self.select{ |x| x.to_i.even? }
end
def odd
self.select{ |x| x.to_i.odd? }
end
end
Precise / Elegant Solution(s)
This one’s by ant0 (and other people).
class Array
def square
map {|x| x*x}
end
def cube
map {|x| x**3}
end
def average
sum / size
end
def sum
reduce(:+)
end
def even
select(&:even?)
end
def odd
select(&:odd?)
end
end
Here’s another interesting solution by adamaig
class Array
def square
collect {|x| x * x }
end
def cube
collect {|x| x * x * x }
end
def sum
inject(0) {|x,y| x + y }
end
def average
sum / length
end
def even
select {|x| 0 == x % 2 }
end
def odd
reject {|x| 0 == x % 2 }
end
end
Extending Ruby Classes
Class, and module definitions in ruby are executable code. They’re parsed at compile time, and executed at runtime. Ruby is different than most other languages, in this regard. This makes it super easy to extend default functionality of classes, and modules. Read more here.