欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ruby  

程序员文章站 2022-07-14 12:33:32
...
ruby的if else如何写:
if x < 10
    puts "Below 10"
elsif x > 20
    puts "Over 20"
else
    puts "10-20"
end


另一种写法
puts "this is kevin" if name == "kevin"

boolean ? code1 : code2

case test_value
when value
 ...
when value
...
else
....
end


流程控制:
break = Teminate the whole loop
next = Jump to the next loop
redo = Redo this loop
retry = Start the whole loop over

break例子:
x = 0
loop do 
    x += 2
    break if x >= 20
    puts x
end


next例子
loop do 
    x += 2
    break if x >= 20
    next if x == 6
    puts x
end


while例子
while boolean
....
end

until boolean
...
end
  
Iterator:
5.times do
    puts "Hello"
end

5.times {puts "Hello"}

1.upto(5) {puts "Hello"}

5.downto(1) {puts "hello"}

(1..5).each{puts "Hello"}

1.upto(5) do |i|
    puts "Hello" + i.to_s
end

fruits = ['banana', 'apple', 'pear']
fruits.each do |fruit|
    puts fruit.capitalize
end

for fruit in fruits
    puts fruit.capitalize
end

array = [1,2,3]
array.each {|num| puts num * 20}