Ruby: counters, counting and incrementing
If you've seen my previous questions, you already know that I am very versatile when it comes to Ruby. So, I opened this site which is for C programming, but I thought that anything that can be done in C should be possible in Ruby (and more readable).
The challenge is to print out a bunch of numbers. I discovered this great .upto () method and I used a block (and actually figured out its purpose). However, I got unexpected behavior in IRb.
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 from: => 1: S Should I do it differently? I expect to get this result:
1 2 3 4 5 6 7 8 9 10
Thanks for your responses, comments and feedback!
a source to share
I have no idea where => 1 comes from
Do not worry. By default, irb
prints the return value of the method execution.
Even if you don't write an operator return
(for example, in C), Ruby returns the value of the last operator evaluated.
In this case, it was 1
What all.
For example try:
class WhereIsTheReturn
def uh?
14 * 3 # no return keyword
end
end
whereIsIt = WhereIsTheReturn.new
hereItIs = whereIsIt.uh?
print "Here it is : #{hereItIs}\n"
a source to share
"=> 1" is IRB, not your code. After every statement you enter into IRB, it prints the result of that statement after the "=>" prompt.
Try to print a new line in your function:
def run
1.upto(10) { |x| print x.to_s + " " }
print "\n"
end
Then it will look like this:
irb> q.run
1 2 3 4 5 6 7 8 9 10
=> nil
a source to share