基础
- puts 显示文本后另起一行,而 print 不会
- everthing在Ruby里都是对象,所以它们都包含内置methods
- 用"."来调用方法
- "#"单行注释
- 多行注释
=begin
This is
a comment
!
=end 命名规范
- 局部变量 : 小写字母 ,用 _ 分割Words
name.method1.method2.medthod3
String Method
- length, reverse, upcase, downcase, capitalize
- include? "words" 判断字符串中是否含有words , 返回值为true或false
- gsub(/word1/, "word2") 用word2替换字符串中的word1
- gsub 是 global substitution(全局替换)
格式化文本
gets 完成后自动添加一个换行符,调用方法chomp会删除额外的换行符.如图,若不删除可能会引起错误
格式化输出"#{variable_name}"
name.method! 感叹号的修饰表示调用method修改name自身值
控制流
一定不要忘记end !!!
1.if/elsif/else
if condition
content
elsif condition
content
else
content
end
Ruby不关心content是否有空格,不过惯例是2个空格
2.unless/else
如果unless语句是false则执行,否则执行else
unless condition
content
else
content
end
unless 和 if 还可以添加到一条语句后面,表明语句在何种条件下执行
puts "if condition is false" unless condition
puts "if condition is true" if condition
循环和迭代
while 运行条件为true
while condition
content
end
until 运行条件为false
until condition
content
end
for in
#从1到9
for num in 1...10
puts num
end
#从1到10
for num in 1..10
puts num
end