第一章ide
字符串,數字,類和對象spa
爲了證實Ruby真的好用,hello world也能寫的如此簡潔:code
puts 'hello world'
1.輸入/輸出對象
print('Enter your name') name=gets() puts("Hello #{name}")
注:Ruby是區分大小寫的blog
2.String類ip
puts("Hello #{name}")中的變量 name是內嵌在整個String裏的,經過 #{ } 包裹進行內嵌求值,並用雙引號""包裹(若是隻是單引號''只會返回字面值)。不只是變量,你甚至能夠嵌入"\t""\n"和算數表達式。字符串
puts "Hello #{showname}" puts( "\n\t#{(1+2) * 3}\nGoodbye" )
3.if……then 語句get
taxrate = 0.175 print "Enter price (ex tax): " s = gets subtotal = s.to_f if (subtotal < 0.0) then subtotal = 0.0 end tax = subtotal * taxrate puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"
4.val、$val、@val的區別it
val是局部變量,$val是全局變量,@val是實例變量io
實例變量就至關於成員變量
5.如何定義一個class
看兩段代碼
class Dog def set_name( aName ) @myname = aName end def get_name return @myname end def talk return 'woof!' end end
class Treasure def initialize( aName, aDescription ) @name = aName @description = aDescription end def to_s # override default to_s method "The #{@name} Treasure is #{@description}\n" end end