Ruby: counters, counting and incrementing
Question
If you have seen my previous questions, you'd already know I am a big nuby when it comes to Ruby. So, I discovered this website which is intended for C programming, but I thought whatever one can do in C, must be possible in Ruby (and more readable too).
The challenge is to print out a bunch of numbers. I discovered this nifty method .upto() and I used a block (and actually understanding its purpose). However, in IRb, I got some unexpected behavior.
class MyCounter
def run
1.upto(10) { |x| print x.to_s + " " }
end
end
irb(main):033:0> q = MyCounter.new
=> #<MyCounter:0x5dca0>
irb(main):034:0> q.run
1 2 3 4 5 6 7 8 9 10 => 1
I have no idea where the => 1 comes from :S Should I do this otherwise? I am expecting to have this result:
1 2 3 4 5 6 7 8 9 10
Thank you for your answers, comments and feedback!
Solution
I have no idea where the => 1 comes from
Don't worry. By default irb
prints the returning value of the execution of the method.
Even if you don't write the return
statement ( like in C for instance ) Ruby returns the value of the last computed statement.
In this case it was 1
That's all.
For instance try:
class WhereIsTheReturn
def uh?
14 * 3 # no return keyword
end
end
whereIsIt = WhereIsTheReturn.new
hereItIs = whereIsIt.uh?
print "Here it is : #{hereItIs}\n"
OTHER TIPS
The "=> 1" is from IRB, not your code. After every statement you type into IRB, it prints the result of that statement after a "=>" prompt.
Try printing a newline in your function:
def run
1.upto(10) { |x| print x.to_s + " " }
print "\n"
end
Then it'll look like this:
irb> q.run
1 2 3 4 5 6 7 8 9 10
=> nil