為了證明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里的,通過 #{ } 包裹進(jìn)行內(nèi)嵌求值,并用雙引號""包裹(如果只是單引號''只會返回字面值)。不僅是變量,你甚至可以嵌入"\t""\n"和算數(shù)表達(dá)式。
復(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()
您可能感興趣的文章:- 詳解Ruby中正則表達(dá)式對字符串的匹配和替換操作
- Ruby的字符串與數(shù)組求最大值的相關(guān)問題討論
- Ruby中的字符串編寫示例
- Ruby中操作字符串的一些基本方法
- Ruby中常用的字符串處理函數(shù)使用實例
- Ruby中創(chuàng)建字符串的一些技巧小結(jié)
- Ruby中實現(xiàn)把字符串轉(zhuǎn)換為類的2種方法
- Ruby中字符串左側(cè)補(bǔ)零方法實例
- Ruby字符串、條件、循環(huán)、數(shù)組、Hash、類基本操作筆記
- Ruby 字符串處理
- Ruby編寫HTML腳本替換小程序的實例分享