為了證明Ruby真的好用,hello world也能寫的如此簡潔:
復制代碼 代碼如下:
puts 'hello world'
1.輸入/輸出
復制代碼 代碼如下:
print('Enter your name')
name=gets()
puts("Hello #{name}")
注:Ruby是區分大小寫的
2.String類
puts("Hello #{name}")中的變量 name是內嵌在整個String里的,通過 #{ } 包裹進行內嵌求值,并用雙引號""包裹(如果只是單引號''只會返回字面值)。不僅是變量,你甚至可以嵌入"\t""\n"和算數表達式。
復制代碼 代碼如下:
puts "Hello #{showname}"
puts( "\n\t#{(1+2) * 3}\nGoodbye" )
3.if……then 語句
復制代碼 代碼如下:
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與之對應,而then可選,除非它與if在同一行。
2.to_f()方法對值為浮點數的String返回浮點數本身,對于不能轉化者返回 0.0
4.val、$val、@val的區別
val是局部變量,$val是全局變量,@val是實例變量
實例變量就相當于成員變量
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
1.成員變量需用@標示
2.無參方法可以不加()
3.每個類要用end結束
4.默認有無參構造器initialize(),也可以重寫帶參數的initialize()
您可能感興趣的文章:- 詳解Ruby中正則表達式對字符串的匹配和替換操作
- Ruby的字符串與數組求最大值的相關問題討論
- Ruby中的字符串編寫示例
- Ruby中操作字符串的一些基本方法
- Ruby中常用的字符串處理函數使用實例
- Ruby中創建字符串的一些技巧小結
- Ruby中實現把字符串轉換為類的2種方法
- Ruby中字符串左側補零方法實例
- Ruby字符串、條件、循環、數組、Hash、類基本操作筆記
- Ruby 字符串處理
- Ruby編寫HTML腳本替換小程序的實例分享