練習1 puts 'Hello there, and what \' s your name?' name = gets.chomp puts 'Your name is ' + name + '? What a nice name!' puts 'Pleased to meet you, ' + name + '. :)'
CASE aaa =[ 1 , 'abc' , 1.3 ] p aaa printf( ' 你要確認哪一個 ?' ) idx = gets.to_i case aaa[idx] when String puts " 這是一個字串 " when Integer puts " 這是一個整數 " when Float puts " 這是一個浮點數 " when Numeric puts ' 這是一個數字 ' else puts " 這是其它類型的物件 " end
110.
三元運算子 EXPRESSION ?(True Condition):(False Condition) a = 10 ; b = 100 a > b ? ( "#{a} > #{b}" ):( "#{a} < #{b}" ) #=> "10 < 100"
111.
迴圈 10 .times do puts ' 那很好啊 ' end for i in 1 .. 10 puts i end x = 100 while x > 10 x = x - 10 puts x end x = 100 until x <= 10 x = x – 10 next if x == 50 # 跳過下一步繼續 puts x end abc = [ 1 , 2 , 3 ] loop do abc.pop p abc break if abc.empty? # 跳出 end
定義類別 class Duck def initialize (name) @name = name end def quack # 實體方法 "#{ @name } is quacking!" end end d = Duck .new( ' 唐老鴨 !' ) puts d.quack # 唐老鴨 ! is quacking! 建構式 ! 物件實體變數
142.
定義類別 class Car @@amount = 0 def initialize (name) @name = name @@amount += 1 end def name= (val) @name = val end def name @name end def self . amount @@amount end end c1 = Car .new( ' 霹靂車 ' ); c2 = Car .new( ' 火戰車 ' ) c3 = Car .new( 'Focus' ); c3.name = 'Focus ST' puts " 現在有 " + Car .amount.to_s + " 台車了 " 物件類別變數 實體方法
143.
類別定義內也可以執行程式 class Car @@amount = 0 def initialize (name) @name = name @@amount += 1 end attr_accessor :name def self . amount @@amount end end class Car @@amount = 0 def initialize (name) @name = name @@amount += 1 end def name= (val) @name = val end def name @name end def self . amount @@amount end end =
私有/保護 定義方式 class Abc def pub ... end def priv ... end def prot ... end private :priv public :pub protected :prot end class Abc public def pub ... end private def priv ... end protected def prot ... end end =
繼承類別 class Vehicle attr_accessor :tires end class Tire attr_accessor :size end class Car < Vehicle def initialize (name) @tires = [] 4 .times{ @tires << Tire .new} end end class Motorcycle < Vehicle def initialize (name) @tires = [] 2 .times{ @tires << Tire .new} end end