使用 irb

, at February 1st, 2008 by 小影

Ruby 其中一個好用的工具是 irb – Interactive Ruby。

它是一個 shell ,同時是 Ruby 的 environment。當你想要驗證一些想法時,你可以直接在 irb 中輸入 statement :

core siuying$ irb
irb(main):001:0> 5.times { puts "Hello!" }
Hi!
Hi!
Hi!
Hi!
Hi!
=> 5

想找第十個費布納西數列的數?

irb(main):002:0> x, y = 0, 1
irb(main):003:0> 10.times do
irb(main):004:1* puts y
irb(main):005:1> x, y = y, x + y
irb(main):006:1> end
1
1
2
3
5
8
13
21
34

你可以立即看到程式中的資料,甚至可以動態地改變物件的行為。比如說我們有這樣一個 class:


class Hello
  def self.greet
    puts "Hi!"
  end
end

這個 class 的功能很簡單:

irb(main):004:0> Hello.greet
Hi!

在 irb 中我們可以動態改變它的行為:

irb(main):006:0> class Hello
irb(main):007:1> def self.greet
irb(main):008:2> puts "Hello, world!"
irb(main):009:2> end
irb(main):010:1> end
=> nil
irb(main):011:0> Hello.greet
Hello, world!

我們可以立即更改源碼,立即測試,不用 compile 不用 build,在開發的初期摸索的過程這尤其有用!

想試試 Ruby 和 irb ?你可以在 browser 中直接執行,保證讓你五分鐘內學會 Ruby!(至少是 Hello World 吧?)

Reference

From Java to Ruby, Bruce Tate, Pragmatic Bookshelf,使用了書中的 fib 算法。同時列出相似功能的 Java 源碼以供參考 :


class Fib {
  public static void main (String[] args) {
    int x = 0;
    int y = 0;
    int total = 1;
    for (int i=0; i<10; i++) {
      System.out.println(total);
      total = x + y;
      x = y;
      y = total;
    }
  }
}

如果想要計更大的 fib,以上程式還有一個隱藏的 bug ,你看到嗎?

相關文章

Post a Comment