2010-10-04 74 views
3

我已經挖過一些紅寶石創業板代碼,我碰到這些和不知道他們是什麼意思什麼是!!和Ruby中的其他一些東西?

def success? 
    [email protected] 
end 

def failure? 
    [email protected] 
end 

cattr_accessor :test_response 

,最後這個塊的代碼

class_inheritable_accessor :attributes 
self.attributes = [] 

def self.attribute(name, options={}) 
    top_level_name = name.to_s.split(".").last.underscore 
    define_method top_level_name do 
    read_attribute name 
    end 

如果你只知道一兩處,這就是罰款...我只是想了解他們...謝謝

+0

爲了使用谷歌搜索,'!'被稱爲bang運算符。 – 2010-10-04 08:40:38

+1

可能重複[什麼!意思是在紅寶石?](http://stackoverflow.com/questions/524658/what-does-mean-in-ruby) – 2010-10-09 21:16:32

回答

6

!!是「中投爲布爾值」。 !否定值,!!否定否定值。因此!!將任何值轉換爲布爾值。

> 5 
=> 5 
> !5 
=> false 
> !!5 
=> true 
> !!5 == true 
=> true 
+0

不只是'!'是'投到布爾',「!!」只是否定了第一個'!' (將值轉換爲布爾值) – 2010-10-04 02:18:19

+2

@Rishav「cast to boolean」,如「轉換爲* equivalent * boolean value」所示。不知道是否可以將'!'稱爲演員,因爲該值完全相反。儘管如此,這確實很好。 – deceze 2010-10-04 02:21:25

+2

@Rishav:如果'@@ success'是一個字符串,'x ='TRUE'; !! x;'會產生'true'而不是'TRUE''。 '!@ success'會返回'false',但發出警告。 – 2010-10-04 02:48:13

3

什麼部分具體你不明白在第二部分的代碼?

第一段中的方法success?failure?返回與@success實例屬性有關的返回布爾值(true/false)。

cattr_accessor創建一個名爲test_response

這裏讀/寫類屬性的,這也是解釋多一點更好的信息:http://apidock.com/rails/Class/cattr_accessor

相關問題