為了證明Ruby真的好用,hello world也能寫的如此簡潔:
復(fù)制代碼 代碼如下:
puts 'hello world'
1.輸入/輸出
復(fù)制代碼 代碼如下:
print('Enter your name')
name=gets()
puts("Hello #{name}")
注:Ruby是區(qū)分大小寫的2.String類
puts("Hello #{name}")中的變量 name是內(nèi)嵌在整個String里的,通過 #{ } 包裹進行內(nèi)嵌求值,并用雙引號""包裹(如果只是單引號''只會返回字面值)。不僅是變量,你甚至可以嵌入"/t""/n"和算數(shù)表達式。
復(fù)制代碼 代碼如下:
puts "Hello #{showname}"
puts( "/n/t#{(1+2) * 3}/nGoodbye" )
3.if……then 語句
復(fù)制代碼 代碼如下:
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}"
1.每個if須有end與之對應(yīng),而then可選,除非它與if在同一行。
2.to_f()方法對值為浮點數(shù)的String返回浮點數(shù)本身,對于不能轉(zhuǎn)化者返回 0.0
4.val、$val、@val的區(qū)別
val是局部變量,$val是全局變量,@val是實例變量
實例變量就相當(dāng)于成員變量
5.如何定義一個class
看兩段代碼
復(fù)制代碼 代碼如下:
class Dog
def set_name( aName )
@myname = aName
end
def get_name
return @myname
end
def talk
return 'woof!'
end
end
復(fù)制代碼 代碼如下:
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
1.成員變量需用@標(biāo)示
2.無參方法可以不加()
3.每個類要用end結(jié)束
4.默認(rèn)有無參構(gòu)造器initialize(),也可以重寫帶參數(shù)的initialize()