Is class required while experimenting Ruby codes in file?

Dear Rubyists,

There I was trying to guide a very good friend of mine, Sajin Shakya who was keen to learn a programming language, Ruby On Rails. I suggested him not to jump onto Rails and dig deep into Ruby first. Hence, as he had learnt C programming earlier, I told him to practice developing similar algorithms he’d previously learnt in his academics through Ruby.

So, he created a method which would calculate the factorial of given number as follows:

[code language=”ruby”]
require “benchmark”
puts Benchmark.measure{
def fact(n)
if n == 0
1
else
n * fact(n-1)
end
end
(1..50000).each do |n|
end
puts fact(“5″)
}
[/code]

The benchmark seen was added later to check the performance of the code snippet in comparison to that I suggested to him which looks like this:

[code language=”ruby”]
require “benchmark”
puts Benchmark.measure{
class Integer
def fact
n=self
if n == 0
1
else
n * (n-1).fact
end
end
end
(1..50000).each do |n|
end
puts “7”.fact
}
[/code]

My first thought before suggesting was if the method definition would work without class definition or not. But to my surprise it was working fine. Then he questioned me why we should be defining the method within the Integer class rather than defining it externally as he’d done. Also, his thought was that it would reduce the line of code as defining class would not be required.

I convinced him with how important the class could be to make our coding life easier but he resisted that in this case it was not required to define the class. Now, our focus was on if the particular change was required to experiment ruby codes in file or not. Hence, the question arose “Is class required while experimenting Ruby codes in file?”.

We benchmarked and noted the difference with the performance but it was not that noticeable. Then, we moved on to figuring out what the difference we could get from these two routes.

The difference noted was that the method were defined within specific class meaning that only that particular class would get the defined method and hence, the error would pop-up immediately if the method implementation was made in a wrong class. And since we’d always have integer to calculate the factorial it seemed legible.

In the first case if a “string” was provided to the method then it would pop-up the error after running through the codes in the method. But in second case it would not bother to run through the codes as it is a “string” and the method is defined for the “integer”. The errors observed can be seen below.

checking the difference

Please feel free to comment your thoughts and help us figure out.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *