Ruby語言 (一)

#=> Hello World      

    標準版:    print "hello world!"

    太長了:    puts "hello world!"

    再短一點:    p "hello world!"

#=> Comment

    # say hello

    =begin
      this is a long comment
    =end

#=> 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


#=> condition if

    質樸的if:
	
    if(a>5)
      puts a
    end

    一行版:

    if a > 5 then puts a end

    語義不夠順暢:    puts a if a > 5

#=> condition unless

    與if語義相反的unless

    puts "miss it" if !name

    puts "miss it" unless name

    三元不能少:    a > 5 ? puts(a) : "oh no"

#=> 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

發佈了53 篇原創文章 · 獲贊 9 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章