Ruby Kata: Function To Generate A Tribonnaci Sequence Until n.

Extending The Built-In Ruby Classes.

BY indefiniteloop

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.

View Kata & Test Cases

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.

——> Sign yourself up here!

I really do hate spam as much as you. Your email will never be shared with anyone, or any party. That's a pinky promise!

• Generating A Tribonacci Series

Apr 14, 2016 in Code
• Sum Of All Natural Numbers, Below N, That Are Multiples of 3 & 5.

Mar 24, 2016 in Code
• Finding The Next Perfect Square.

Mar 17, 2016 in Code 