简体   繁体   English

Ruby:计数器,计数和递增

[英]Ruby: counters, counting and incrementing

If you have seen my previous questions, you'd already know I am a big nuby when it comes to Ruby. 如果您曾经看过我以前的问题,那么您在使用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). 因此,我发现了这个旨在进行C编程的网站,但我认为任何用C语言可以做的事,都必须在Ruby中实现(并且也更具可读性)。

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). 我发现了这个漂亮的方法.upto(),并且使用了一个块(并且实际上了解了它的用途)。 However, in IRb, I got some unexpected behavior. 但是,在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 the => 1 comes from :S Should I do this otherwise? 我不知道=> 1来自哪里:S我应该这样做吗? 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! 感谢您的回答,评论和反馈!

The "=> 1" is from IRB, not your code. “ => 1”来自IRB,而不是您的代码。 After every statement you type into IRB, it prints the result of that statement after a "=>" prompt. 在您键入IRB的每个语句之后,它将在“ =>”提示后打印该语句的结果。

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

I have no idea where the => 1 comes from 我不知道=> 1来自哪里

Don't worry. 不用担心 By default irb prints the returning value of the execution of the method. 默认情况下, irb打印该方法执行的返回值。

Even if you don't write the return statement ( like in C for instance ) Ruby returns the value of the last computed statement. 即使您不编写return语句(例如在C中),Ruby也会返回最后一个计算语句的值。

In this case it was 1 在这个例子中是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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM