ri String#chomp
a =b= c
puts "a=#{a} b=#{b} c=#{c}"
a =1 b=2 c=6
#{ }在双引号下起作用
平行赋值a=b=c
1. 条件表达式
print ' Enter something: '
str = gets
if str .chomp == ' p'
puts ' You entered a p!'
else
puts " You entered #{str.chomp} bye "
end
print ' Enter somthing else: '
str = gets
case str
when ' p'
puts ' You entered a p!'
when ' 1'
puts ' You entered a 1. That is a number'
else
puts " You entered a #{str}. "
end
调用系统命令:
puts `dir`
该符号与~同一个键
2.循环:
while i > 0
print " #{i} "
i += 1
if i > 9
break
end
end
puts
for var in 1 .. 9
print " #{var} "
end
puts
9 .times do |var|
var = var + 1
print " #{var} "
end
puts
1 .upto( 9 ) do |var|
print " #{var} "
end
puts
1 .step( 9 , 3 ) do |var|
print " #{var} "
end
int.times {|i| block } => int
-----------------------------------------------------------------------
Iterates block int times, passing in values from zero to int - 1.
5.times do |i|
print i, " "
end
produces:
0 1 2 3 4
int.upto(limit) {|i| block } => int
-----------------------------------------------------------------------
Iterates block, passing in integer values from int up to and including limit.
5.upto(10) { |i| print i, " " }
produces:
5 6 7 8 9 10
使用fxri来查询#step
num.step(limit, step ) {|i| block } => num
-----------------------------------------------------------------------
Invokes block with the sequence of numbers starting at num, incremented by step on each call. The loop finishes when the value to be passed to the block is greater than limit (if step is positive) or less than limit (if step is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed floor(n + n*epsilon)+ 1 times, where n = (limit - num)/step. Otherwise, the loop starts at num, uses either the < or > operator to compare the counter against limit, and increments itself using the + operator.
1.step(10, 2) { |i| print i, " " }
Math::E.step(Math::PI, 0.2) { |f| print f, " " }
produces:
1 3 5 7 9
2.71828182845905 2.91828182845905 3.11828182845905