首页 > 代码库 > ruby 基础笔记

ruby 基础笔记

变量定义(variables):

local: time or _time  instance: @time  class: @@time  global $time

数据类型(data types)

Numeric  String  Symbol  Boolean  Array  Hash 

variables tricks(变量应用)

"hello #{name}"  a,b = b,a  3.times{ puts "hello"}  "hello" * 3

判断语句

1.condition if

质樸的if:

  if(a>5)

     puts a

  end

一行版:

  if a > 5 then puts a end

语义不够顺畅:

  puts a if a > 5

2.condition unless

  • 与if语义相反的unless

  puts "miss it" if !name

  puts "miss it" unless name

  三元不能少:  

  a > 5 ? puts(a) : "oh no"

3.condition if else

  

  • if elsif else:

  • 
    if name == "jack"
      "i am rose"
    elsif name == "rose"
      "jack i miss u"
    else
      "get out from here"
    end
      
  • 这个肯定是switch的场景啊:

  • 
    case name
    when "jack" then "i am rose"
    when "rose" then "jack i miss u"
    else "get out from here"
    end

loop(循环)

  • 循环怎么写:

  • 3.times{ puts "hello world" }
  • for呢:

  • 
    for x in [1,2,3]
      puts x
    end
  • while:

  • 
    while i > 5 do
      i -= 1
    end
    i -= 1 while i > 5
    		
  • while的好兄弟until:

  • 
    until i <= 5 do
      i -= 1
    end
    i -= 1 until i<= 5
    • while true太不洋气了:

    • 
      loop do
        puts "我自豪"
      end
      		
    • 打断罪恶的连锁:

    • break
      next
      redo
      retry