Ruby 程式語言簡介. IRB(Interactive Ruby) irb(main):001:0> irb(main):001:0> 1 + 1 2 puts...
-
Upload
melissa-caldwell -
Category
Documents
-
view
227 -
download
2
Transcript of Ruby 程式語言簡介. IRB(Interactive Ruby) irb(main):001:0> irb(main):001:0> 1 + 1 2 puts...
Ruby 程式語言簡介
IRB(Interactive Ruby)
irb(main):001:0>irb(main):001:0> 1 + 1Þ2
puts "Hello, World!!"
$ ruby hello.rb
程式語言分類/* PHP */$i = 1;echo "Value is " + $i# 1
/* C */int a = 5;float b = a;
# Rubyi=1puts "Value is " + i
#TypeError: can't convert Fixnum into String# from (irb):2:in `+'# from (irb):2
整數 Integer 浮點數 Float
54.3210.001-12.3120.0
5-20599999999990
四則運算puts 1.0 + 2.0puts 2.0 * 3.0puts 5.0 - 8.0puts 9.0 / 2.0
# 3.0# 6.0# -3.0# 4.5
puts 1 + 2puts 2 * 3puts 5 - 8puts 9 / 2
# 3# 6# -3# 4
puts 5 * (12-8) + -15puts 98 + (59872 / (13*8)) * -52
字串 String
puts 'Hello, world!'puts ''puts 'Good-bye.'
puts 'I like ' + 'apple pie.'puts 'You\'re smart!'
puts '12' + 12 #<TypeError: can't convert Fixnum into String>
var1 = 'stop'var2 = 'foobar'var3 = "aAbBcC"
puts var1.reverse # 'pots'puts var2.length # 6puts var3.upcaseputs var3.downcase
Ruby 完全地物件導向# 輸出 "UPPER"puts "upper".upcase
# 輸出 -5 的絕對值puts -5.abs
# 輸出 Fixnum 類別puts 99.class
# 輸出 "Ruby Rocks!" 五次5.times do puts "Ruby Rocks!"end
區域變數 Local Variable
composer = 'Mozart'puts composer + ' was "da bomb", in his day.'
my_composer = 'Beethoven'puts 'But I prefer ' + my_composer + ', personally.'
型別轉換 Conversions
var1 = 2var2 = '5'
puts var1.to_s + var2 # 25puts var1 + var2.to_i # 7
puts 9.to_f / 2 # 4.5
常數 Constant
Foo = 1Foo = 2 # (irb):3: warning: already initialized constant Foo
RUBY_PLATFORM # => "x86_64-darwin10.7.0"ENV # => { "PATH" => "....", "LC_ALL" => "zh_TW.UTF-8" }
空值 nil
nil # nilnil.class # NilClass
nil.nil? # true42.nil? # false
nil == nil # truefalse == nil # false
註解 Comment
# this is a comment line# this is a comment line
=begin This is a comment line This is a comment line=end
陣列 Array
a = [ 1, "cat", 3.14 ]
puts a[0] # 輸出 1puts a.size # 輸出 3
a[2] = nilputs a.inspect # 輸出 [1, "cat", nil]a[99] # nil
colors = ["red", "blue"]
colors.push("black")colors << "white"puts colors.join(", ") # red, blue, black, white
colors.popputs colors.last #black
雜湊 Hash
config = { "foo" => 123, "bar" => 456 }puts config["foo"] # 輸出 123config["nothing"] # 是 nil
config = { foo: 123, bar: 456 } # 等同於 { :foo => 123, :bar => 456 }
字串符號 Symbols
config = { :foo => 123, :bar => 456 }puts config[:foo] # 輸出 123
"foobar".object_id # 2151854740"foobar".object_id # 2151830100:foobar.object_id # 577768:foobar.object_id # 577768
比較方法puts 1 > 2 # 大於puts 1 < 2 # 小於puts 5 >= 5 # 大於等於puts 5 <= 4 # 小於等於puts 1 == 1 # 等於puts 2 != 1 # 不等於
puts ( 2 > 1 ) && ( 2 > 3 ) # 和puts ( 2 > 1 ) || ( 2 > 3 ) # 或
控制結構 If
if account.total > 100000 puts "large account"elsif account.total > 25000 puts "medium account"else puts "small account"End
puts "greater than ten" if total > 10
三元運算子x = 3if x > 3 y = "foo"else y = "bar"End
x = 3y = ( x > 3 )? "foo" : "bar"
控制結構 Case
case name when "John" puts "Howdy John!" when "Ryan" puts "Whatz up Ryan!" else puts "Hi #{name}!"end
迴圈# while 用法範例:i=0while ( i < 10 ) i += 1 next if i % 2 == 0 # 跳過雙數End
# until 用法範例:i = 0i += 1 until i > 10puts i# 輸出 11
# loop 用法範例:i = 0loop do i += 1 break if i > 10 # 中斷迴圈end
真或假 True or False
puts "not execute" if nilputs "not execute" if false
puts "execute" if true # 輸出 executeputs "execute" if “” # 輸出 execute ( 和 JavaScript 不同 )puts "execute" if 0 # 輸出 execute ( 和 C 不同 )puts "execute" if 1 # 輸出 executeputs "execute" if "foo" # 輸出 executeputs "execute" if Array.new # 輸出 execute
方法定義 Methods
def say_hello(name) result = "Hi, " + name return resultend
puts say_hello('ihower')# 輸出 Hi, ihower
def say_hello(name) "Hi, " + nameend
say_hello 'ihower'
? 與 ! 的慣例array=[2,1,3]
array.empty? # falsearray.sort # [1,2,3]
array.inspect # [2,1,3]
array.sort! # [1,2,3]array.inspect # [1,2,3]
類別 Classes
color_string = String.new color_string = "" # 等同
color_array = Array.newcolor_array = [] # 等同
color_hash = Hash.newcolor_hash = {} # 等同
time = Time.new # 內建的時間類別puts time
類別 Classes
class Person # 大寫開頭的常數
def initialize(name) # 建構式 @name = name # 物件變數 end
def say(word) puts "#{word}, #{@name}" # 字串相加 end
end
p1 = Person.new("ihower")p2 = Person.new("ihover")
p1.say("Hello") # 輸出 Hello, ihowerp2.say("Hello") # 輸出 Hello, ihover
方法封裝class MyClass def public_method end private def private_method end protected
def protected_method endend
Class 繼承class Pet attr_accessor :name, :age def say(word) puts "Say: #{word}" endend
class Cat < Pet def say(word) puts "Meow~" super endend
class Dog < Pet def say(word, person) puts "Bark at #{person}!" super(word) endend
Cat.new.say("Hi")Dog.new.say("Hi", "ihower")輸出Meow~Say: HiBark at ihower!Say: Hi
迭代器 Iterator
languages = ['Ruby', 'Javascript', 'Perl']languages.each do |lang| puts "I love #{lang}!"end# I Love Ruby# I Love Javascript# I Love Perl
# 反覆三次3.times do puts 'Good Job!'end# Good Job!# Good Job!# Good Job!
# 從一數到九1.upto(9) { |x| puts x }
# 多一個索引區塊變數languages = ['Ruby', 'Javascript', 'Perl']languages.each_with_index do |lang, i| puts "#{i}, I love #{lang}!"end# 0, I Love Ruby# 1, I Love Javascript# 2, I Love Perl
3.times { puts "Hello" }
迭代器 Iterator
# 迭代並造出另一個陣列a = [ "a", "b", "c", "d" ]b = a.map {|x| x + "!" }puts b.inspect
# 結果是 ["a!", "b!", "c!", "d!"]
# 找出符合條件的值b = [1,2,3].find_all{ |x| x % 2 == 0 }b.inspect# 結果是 [2]
# 迭代並根據條件刪除a = [51, 101, 256]a.delete_if {|x| x >= 100 }# 結果是 [51]
# 客製化排序[2,1,3].sort! { |a, b| b <=> a }# 結果是 [3, 2, 1]
# 計算總和(5..10).inject {|sum, n| sum + n }
# 找出最長字串 find the longest wordlongest = ["cat", "sheep", "bear"].inject do |memo,word| ( memo.length > word.length )? memo : wordend
迭代器 Iterator
file = File.new("testfile", "r")# ... 處理檔案file.close
File.open("testfile", "r") do |file| # ... 處理檔案end# 檔案自動關閉
Yield
# 定義方法def call_block puts "Start" yield yield puts "End"end
call_block { puts "Blocks are cool!" }# 輸出# "Start"# "Blocks are cool!"# "Blocks are cool!"# "End"
Yield
def call_block yield(1) yield(2) yield(3)end
call_block { |i| puts "#{i}: Blocks are cool!"}# 輸出# "1: Blocks are cool!"# "2: Blocks are cool!"# "3: Blocks are cool!"