Comment Line comments are #Multi-line comments are stranger with = begin and = end
#! / usr / bin / ruby -w
puts "Hello, Ruby!"
= begin
This is a multi-line comment.
Scalable to any number of rows.
But = begin and = end can only appear on the first and last lines.
= end
Conditional judgment
if conditional [then]
code...
[elsif conditional [then]
code...]...
[else
code...]
end
An if expression is used for conditional execution. The value false and nil are false, and the other values are true. Note that Ruby uses elsif, not the else if and elif.
Usually we omit the reserved word then. If you want to write the complete if style in a row, then you must separate the conditional and program chunks with then. As shown below:
If a = = 4 then a = 7 end
Instance
#! / usr / bin / ruby
#-*-coding: UTF-8-*-
x = 1
if x> 2
puts "x is greater than 2"
elsif x <= 2 and x! = 0
puts "x is 1"
else
puts "Unable to know the value of x"
end
Ruby Loop syntax
While conditional [do] codeend
Or
While conditional [:] Codeend
Do or: can omit to write in syntax. But to write down a while in a row, you must separate the conditional or program chunks with do or:.
Grammar
code while condition
or
begin
code
end while conditional
Until is a special until grammar.
Until conditional [do] codeend
Instance
#! / usr / bin / ruby
#-*-coding: UTF-8-*-
$ i = 0
$ num = 5
until $ i> $ num do
puts ("i = # $ i" in a loop statement)
$ i + = 1;
end
Forfor is generally the most used cycle mode
for variable [, variable ...] in expression [do]
code
end
Like what
#! / usr / bin / ruby
#-*-coding: UTF-8-*-
for i in 0..5
puts "The local variable has the value # {i}"
end
You can write it like that.
#! / usr / bin / ruby
#-*-coding: UTF-8-*-
(0..5) .each do | i |
puts "The local variable has the value # {i}"
end
The next statement is equivalent to the Continue statement redo can start the loop again, but it is easy to cause a dead loop, and I don't know why this syntax is designed
#! / usr / bin / ruby
#-*-coding: UTF-8-*-
for i in 0..5
if i <2 then
puts "The local variable has the value # {i}"
redo
end
end
This will produce a dead loop retry statement If retry appears in the rescue clause of the BEGIN expression, start again from the beginning of the body of begin.
begin
do_something # exception thrown
rescue
# Handle errors
retry # restart from begin
end
If the retry appears inside the iteration, within the block, or within the body of the for expression, the iteration call is restarted. The parameters of the iteration are re-evaluated.
for i in 1..5
retry if some_condition # restart from i == 1
end
Instance
#! / usr / bin / ruby
#-*-coding: UTF-8-*-
for i in 1..5
retry if i> 2
puts "The local variable has the value # {i}"
end
And this is another cycle of death.
Interesting ruby-Study notes 2