Ruby基础语法

基础

  1. puts 显示文本后另起一行,而 print 不会
  2. everthing在Ruby里都是对象,所以它们都包含内置methods
  3. 用"."来调用方法
  4. "#"单行注释
  5. 多行注释 =begin
    This is
    a comment
    !
    =end
  6. 命名规范

    1. 局部变量 : 小写字母 ,用 _ 分割Words
  7. name.method1.method2.medthod3



String Method

  1. length, reverse, upcase, downcase, capitalize
  2. include? "words" 判断字符串中是否含有words , 返回值为true或false
  3. gsub(/word1/, "word2") 用word2替换字符串中的word1
    • gsub 是 global substitution(全局替换)



格式化文本

  1. gets 完成后自动添加一个换行符,调用方法chomp会删除额外的换行符.如图,若不删除可能会引起错误
    Screen Shot 2018-07-17 at 9.22.03 P

  2. 格式化输出"#{variable_name}"

  3. 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

猜你喜欢

转载自www.cnblogs.com/CodeAndMoe/p/Ruby.html