函式呼叫
func(param1, param2....) # 跟一般高階語言一樣
func param1, param2..... # 可以不用帶括號
字串處理
exp = /s/ # 第一個參數為 regex
some_string.gsub!(exp, str) # 將 exp match 到的字串更改成 str(有 match 到都會改)
some_string.include?(str) # 字串是否包含某字串,? 表示該函式會回傳 true 或 false
if elsif else
if a == 1
puts "1"
elsif a == 10
puts "2"
else
puts "3"
end
while 迴圈
while i < 5
i++
end
until 迴圈
until i > 5 # 當 i 大於 5 時結束
i++
end
for in 迴圈
for i in 1...5 # 1 <= i < 5
puts i
end
# 若是使用 ".." 則會包含後面的數字
for i in 1..5 # 1 <= i <= 5
puts i
end
loop do 迴圈
i = 20
loop do
i -= 1
print "#{i}"
break if i <= 0 # 條件需寫在 loop 中,若沒有寫則是無窮迴圈
=begin
當然,也可以寫作
if i <= 0
break
end
=end
end
# "next" 跟其他語言的 continue 用法一樣
loop do
next if i % 2 == 1
end
Array
my_array = [1, 2, 3, 4, 5]
Array each
array = [1,2,3,4,5]
array.each do |x|
# do something
end
Times
10.times do |n| # n 從 0 到 9
# do something
end
Like this:
Like Loading...
Related