繁体   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