Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 6e2fb51281
Fetching contributors…

Cannot retrieve contributors at this time

103 lines (73 sloc) 3.571 kb

簡介

這是一個簡短的 Ruby 入門導覽,應該可以在二十分鐘內完成。您必須先安裝好 Ruby (如果還沒有,請先 下載 安裝)

互動式 Ruby

Ruby 附帶了一支程式可以讓你即時看到執行 Ruby 敘述的結果。使用這種互動式環境來學習 Ruby 可說是非常地方便。

打開 IRB (表示 Interactive Ruby)。

  • 如果你使用 Mac OS X 請打開 Terminal 然後輸入 irb 和 enter。
  • 如果你使用 *Linux*,請打開一個 shell 然後輸入 irb 和 enter。
  • 如果你使用 *Windows*,請從開始選單中打開 Ruby 的 fxri
irb(main):001:0>

Ok,打開了,現在怎麼辦?

請輸入:@"Hello World"@

irb(main):001:0> "Hello World" => "Hello World"

讓 Ruby 聽話!

發生什麼事了? 你是不是剛剛寫下了全世界最短的 “Hello World” 程式?也不盡然。第二行只是 IRB 告訴我們最後的敘述執行結果。如果我們需要輸出 “Hello World” 還需要多一行:

irb(main):002:0> puts "Hello World" Hello World => nil

puts 是 Ruby 的基本輸出指令。但是什麼是 => nil 呢? 那是那一行敘述的執行結果。 puts 總是回傳 nil,nil 在 Ruby 中表示一個絕對的空值。

你的第一個免費計算機

其實,我們已經可以用 IRB 來當做一個簡單的計算機了。

irb(main):003:0> 3+2 => 5

三加二,夠簡單了。那怎麼三乘二呢? 你可以試試,一點都不難,你也能夠隨意輸入數字試試。試著按按看 它會顯示上一行的 @3+2@,然後你可以往左移動到 + 更改成 * 乘號。

irb(main):004:0> 3*2 => 6

接下來,讓我們試試看三的平方:

irb(main):005:0> 3**2 => 9

In Ruby ** is the way you say “to the power of”. But what if you
want to go the other way and find the square root of something?

irb(main):006:0> Math.sqrt(9) => 3.0

Ok, wait, what was that last one? If you guessed, “it was figuring out
the square root of nine,” you’re right. But let’s take a closer
look at things. First of all, what’s Math?

Modules, Group Code by Topic

Math is a built-in module for mathematics. Modules serve two roles in
Ruby. This shows one role: grouping similar methods together under a familiar
name. Math also contains methods like sin() and tan().

Next is a dot. What does the dot do? The dot is how you identify the
receiver of a message. What’s the message? In this case it’s
sqrt(9), which means call the method sqrt, shorthand for “square
root” with the parameter of 9.

The result of this method call is the value 3.0. You might notice
it’s not just 3. That’s because most of the time the square root of
a number won’t be an integer, so the method always returns a
floating-point number.

What if we want to remember the result of some of this math? Assign
the result to a variable.

irb(main):007:0> a = 3 ** 2 => 9 irb(main):008:0> b = 4 ** 2 => 16 irb(main):009:0> Math.sqrt(a+b) => 5.0

As great as this is for a calculator, we’re getting away from the traditional
Hello World message that beginning tutorials are supposed to focus on… so let’s go back to that.

Jump to Line
Something went wrong with that request. Please try again.