Ruby 中的 send 方法
    
    
            Stewart Nguyen
    2023年1月30日
    
    Ruby
    Ruby Method
    
 
在 Ruby 中,有幾種方法可以呼叫方法。本文將討論 send 方法的使用及其好處。
在 Ruby 中呼叫沒有 send 方法的方法
    
通常,我們會使用 . 跟在方法名後面來呼叫一個物件的方法。
考慮以下示例:
[1, 2, 3].join
=> "123"
在上面的程式碼片段中,對陣列 [1, 2, 3] 呼叫了 join 方法。使用 . 僅適用於物件的公共方法;呼叫私有方法是不可能的。
在 Ruby 中使用 send 方法呼叫私有方法
要呼叫私有方法,請使用 send 方法。考慮以下程式碼片段。
class Foo
    private
    def secret
        'secret that should not be told'
    end
    def my_asset(amount, location)
        "I have #{amount}$ in #{location}"
    end
end
Foo.new.secret
Foo.new.my_asset(100, 'the basement')
輸出:
NoMethodError: private method 'secret' called for #<Foo>
NoMethodError: private method 'my_asset' called for #<Foo>
我們必須使用 send 方法來呼叫 private 關鍵字下定義的方法。
Foo.new.send(:secret)
Foo.new.send(:my_asset, 100, 'the basement')
輸出:
=> "secret that should not be told"
=> "I have 100$ in bank"
send 方法的第一個引數是方法名稱,可以是字串或符號。origin 方法的引數也通過第二個和第三個引數接受,依此類推。
在 Ruby 中使用 send 方法在執行時呼叫方法
當有儲存方法名稱的變數時,send 會派上用場。
例子:
class Report
    def format_xml
        'XML'
    end
    def format_plain_text
        'PLAIN TEXT'
    end
end
def get_report_format(extension)
    if extension == 'xml'
        'format_xml'
    else
        'format_plain_text'
    end
end
report_format = get_report_format('xml')
report = Report.new
formated_report = report.send(report_format)
輸出:
"XML"
Report 類負責生成上例中的格式。它支援 format_xml 和 format_plain_text。
我們還有一個名為 get report_format 的方法,它返回 Report 支援的格式。
我們不能使用 . 直接呼叫 format_xml 的符號。相反,我們必須使用 send 函式:report.send(report format)。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe