接受用户输入
首字母大写
字母变大写
字母变小写
多行输出
# 多行输出
EOF
注释
变量获取
变量
全局变量 $
类变量 @@
方法变量 @
局部变量 小写字母或_
if/else
puts ‘1’
elsif b < a
puts ‘2’
end
类
def functionname(params)
puts params
end
end
class1=Classname.new
class1.functionname(‘1’)
unless
unless false
print ‘ok’
else
print ‘no’
end
是否包含字符
user_input=gets.chomp
user_input.downcase!
if user_input.include?”s”
print ‘has s’
end
替换字符
user_input.gsub!(/s/,”th”)
在字符串中输出变量值
while
while counter < 11
puts counter
counter=counter + 1
end
Until
until counter > 10
print counter
counter=counter + 1
end
+=、 -=、 *=、 /=
Some languages have the increment operators ++ and — (which also add or subtract 1 from a value), but Ruby does not
for循环
# 如果 1…10 包含1-9,如果 1..10 包含1-10
puts num
end
Loop Method
An iterator is just a Ruby method that repeatedly invokes a block of code.
loop do
i -=1
print “#{ i }”
break if i <=0
end
Next
loop do
i -=1
next if i%2 !=0
print “#{i}”
break if i <=0
end
数组
The .each Iterator迭代器
# one way to loop
numbers.each { |item| puts item }
# another way to loop
numbers.each do |item|
puts item
end
The .times Iterator 次数迭代器
Looping with ‘While’
while num <=50 do
print num
num +=1
end
Looping with ‘Until’
until num > 50 do
print num
num +=1
end
Loop the Loop with Loop
loop do
num +=1
print “Ruby!”
break if num==30
end
The .split Method,
puts “Text to search through: ”
text=gets.chomp
puts “Word to redact”
redact=gets.chomp
words=text.split(” “)
words.each do |word|
print word
end