[英]ruby understanding enum method
我正在閱讀Ruby中的另一個SO問題Enums ,它有以下代碼片段:
class Enum
private
def self.enum_attr(name, num)
name = name.to_s
define_method(name + '?') do
@attrs & num != 0
end
define_method(name + '=') do |set|
if set
@attrs |= num
else
@attrs &= ~num
end
end
end
public
def initialize(attrs = 0)
@attrs = attrs
end
def to_i
@attrs
end
end
據我了解,這是定義一個名為enum_attr
的類方法,這是正確的嗎? 我不確定的是在enum_attr
方法中包含define_method
語句意味着什么。
然后在該帖子上顯示了如下擴展的類
class FileAttributes < Enum
enum_attr :readonly, 0x0001
enum_attr :hidden, 0x0002
end
我不太明白第二部分的作用 - 有人可以解釋一下嗎?
在Enum
,方法enum_attr
在類的單例上定義,並且可用於所有子類。 此方法在類定義主體的范圍內,並且在FileAttributes
使用以下參數調用它:readonly, 0x0001
然后:hidden, 0x0002
。
當enum_attr
(讓我們看一下第一個調用, enum_attr :readonly, 0x0001
),它定義了兩個方法: readonly?
& readonly=(set)
。 調用enum_attr
的結果在功能上等同於在FileAttributes
寫出以下內容:
def readonly?
@attrs & 0x0001 != 0
end
def readonly=(set)
if set
@attrs |= 0x0001
else
@attrs &= ~0x0001
end
end
由於傳遞給define_method
的塊是一個閉包,因此當您調用已定義的方法時,傳遞塊的作用域中的變量num
仍在作用域中。 換句話說,傳入enum_attr
的num
變量在readonly?
生成的方法中仍然可用readonly?
& readonly=
稍后從不同的范圍調用它們。
必須使用define_method
因為正在動態生成方法的名稱(即,我們不知道方法的名稱提前)。
您正在查看一個類方法,該方法生成使用位域存儲的true / false屬性。 你有C(或者Java)的背景嗎? 如果是這樣,你可能熟悉位域和一般“bit twiddling”。 這些主題的大多數互聯網資源都與C有關; 但你仍然可以在Ruby和其他語言中使用它們。
在這種情況下,您不會從將各自的布爾屬性存儲到單個位中獲得任何結果,我建議您不要實際使用此代碼。 最好為每個屬性使用不同的實例變量,使用true
或false
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.