2014年3月29日 星期六

Rails Tutorial - @user ? 實體變數(實例變量)

在Ruby中以@開頭的為實例變量,
@user就是一個實例變量,
它特殊的地方在於它能直接用於view中,
也常用於在同一類別中的不同方法間傳遞值。

舉個例子說明:
當我們使用User.new這個方法時,
會調用:


def initialize(attributes = {})  
    @name = attributes[:name]  
    @email = attributes[:email] 
end
    
而attributes是一個空的hash(雜湊),
為@name和@email這兩個實例變數設定值,
所以在同一類別中的其他方法也能直接調用這兩個實例變數,
像是formatted_email這個方法:


def formatted_email  
    "#{@name} <#{@email}>"
end 

沒有留言:

張貼留言