簡體   English   中英

Ruby - 如何將哈希合並到一個方法中

[英]Ruby - How to Merge a Hash into a method

我有這個方法

def method1
 {
  headers: { 'Content-Type' => 'application/json' }
 }
end

這是將另一個鍵和值合並到這個 method1 哈希中的另一種方法,所以

def merge_hash
  method1.merge!(body: { params: 123 }
end

所以當我再次調用method1時,我希望他返回一個marged body,我的問題是為什么不會發生這種情況或者我該怎么做?

每次調用method1它都會返回一個新對象:

> method1.object_id
=> 47220476550040 
> method1.object_id
=> 47220476543700 

為了實現你想要的,你可以在第一次調用后記住它:

def method1
  @method1 ||= {
    headers: { 'Content-Type' => 'application/json' }
  }
end

> method1.object_id
=> 47220477154400 
> method1.object_id
=> 47220477154400 

我建議不要以這種方式改變散列,因為它會導致錯誤。

當然method1的返回值不會改變,因為你沒有改變方法本身。

您可以使用稱為別名方法鏈的古老而邪惡的技術。

# Define a new method `method1_without_body`
# whose implementation is exactly the same
# as `method1` at this moment.
alias method1_without_body method1

# Define a new method that calls `method1_without_body`.
# Make sure that it does NOT call `method1`,
# or you'll get a stack overflow.
def method1_with_body
  method1_without_body.merge!(body: { params: 123 })
end

# Define a new method `method1`
# whose implementation is exactly the same
# as `method1_with_body`.
# This method shadows the previous implementation of `method1`.
alias method1 method1_with_body

或者,如果您使用的是 Rails < 5,那么只需

def method1_with_body
  method1_without_body.merge!(body: { params: 123 })
end

alias_method_chain :method1, :body

然后當您調用method1 ,它會返回帶有標頭和正文的哈希值。

順便說一下,這個技術從 Rails 5 開始就被棄用了,后來被完全刪除了(我忘了是哪個小版本了)。

也許這與您所看到的很接近:

class MyClass

    attr_reader :method1

    def initialize
      @method1 = {  headers: { 'Content-Type' => 'application/json' } }
    end

    def merge_hash
      @method1.merge!(body: { params: 123 }
    end

end

因此,如果你有一個

o = MyClass.new

第一個o.method1將返回初始散列,但在

o.merge_hash

o.method1將返回修改后的哈希值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM