Share This Item:
    Coding resources

Module: Enumerable (Ruby 2.0.0)

from reddit conversation regarding early stage Ruby best practices:

Q. What is the one thing you wish you knew when starting Ruby?

Denommus
Lots of things. For instance, all the methods that manipulate arrays, like map, reduce, delete_if, keep_if, and how exactly they work.

Want a new array with every int higher than 4 from the old array?

A newbie would do this:

new = []
for x in old do
new << x if x > 4
end

A seasoned developer would simply do this:

new = old.keep_if { |x| x > 4 }

Want the sum of every element of the array?

arr.reduce { |x, y| x+y }

Want a factorial?

Of course you can do the normal way:

def factorial(x)
if x < 1
1
else
x*factorial(x-1)
end
end

But you can also do this:

def factorial(x)
(1..x).reduce(1) { |x, y| x*y }
end

Which will not have stack overflows.

Of course, you can also set this:

RubyVM::InstructionSequence.compile_option = {
:tailcall_optimization => true,
:trace_instruction => false
}

And make this:

def factorial(x)
def fact_helper(x, acc)
if x < 1
acc
else
fact_helper(x-1, x*acc)
end
end
fact_helper(x, 1)
end

And it will not overflow because it is tail-call optimized. But then, the second solution is shorter and effective (and you won't need to set compile options).

mnemoniker
To piggyback on this comment, I once read in a similar post that one of the first things you should do is learn the Enumerable module backwards and forwards. I can't disagree when you see how much code and time is saved.

Comments

    Added to this shelf by: Brian Alford, on 02-10-2014 4:16pm

    Following This Shelf: