Ruby學習-第一章

第一章ide

字符串,數字,類和對象spa

爲了證實Ruby真的好用,hello world也能寫的如此簡潔:code

 

puts 'hello world'

 

1.輸入/輸出對象

print('Enter your name')

name=gets()

puts("Hello #{name}")

    注:Ruby是區分寫的blog

 

2.String類ip

  puts("Hello #{name}")中的變量 name是內嵌在整個String裏的,經過 #{ } 包裹進行內嵌求值,並用雙引號""包裹(若是隻是單引號''只會返回字面值)。不只是變量,你甚至能夠嵌入"\t""\n"和算數表達式。字符串

puts "Hello #{showname}"
puts( "\n\t#{(1+2) * 3}\nGoodbye" )

 

3.if……then 語句get

taxrate = 0.175 
print "Enter price (ex tax): "
s = gets
subtotal = s.to_f
if (subtotal < 0.0) then
    subtotal = 0.0 
end
tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"
  1. 每一個if須有end與之對應,而then可選,除非它與if在同一行。
  2. to_f()方法對值爲浮點數的String返回浮點數自己,對於不能轉化者返回 0.0

 

4.val、$val、@val的區別it

val是局部變量,$val是全局變量,@val是實例變量io

實例變量就至關於成員變量

 

5.如何定義一個class

看兩段代碼

class Dog   
    def set_name( aName )
        @myname = aName
    end
   
    def get_name
         return @myname
    end
    
    def talk
        return 'woof!'
    end
end
class Treasure
      def initialize( aName, aDescription )
        @name         = aName
        @description  = aDescription
      end
      
      def to_s # override default to_s method
           "The #{@name} Treasure is #{@description}\n"
      end
end
  1. 成員變量需用@標示
  2. 無參方法能夠不加()
  3. 每一個類要用end結束
  4. 默認有無參構造器initialize(),也能夠重寫帶參數的initialize()
相關文章
相關標籤/搜索