代码之家  ›  专栏  ›  技术社区  ›  Arcath

将块传递到方法中

  •  0
  • Arcath  · 技术社区  · 16 年前

    我正在研究如何将块传递到方法中。

    基本上我有一个方法,而不是让用户写这个:

    def user_config
        @config[:config_value] = "what they want"
    end
    

    我希望他们能够做到:

    user_config do
        :config_value => "what they want"
    end
    

    2 回复  |  直到 16 年前
        1
  •  3
  •   diegogs    16 年前

    使用yield调用块,因此:

    def user_config
        yield.each do |k, v|
            @config[k] = v
        end
    end
    

    像这样叫

    user_config do
        {:config_value => "what they want"}
    end
    

    {:config_value => "what they want"}
    

    您在散列中获取每个键的值,并在@config散列中分配其值。

        2
  •  3
  •   Milan Novota    16 年前

    尽管@dieggs是对的,而且他的解决方案也能很好地工作,但在这种简单的情况下,我还是避免使用块。

    def user_config(config_hash)
      config_hash.each do |k,v|
        @config[k] = v
      end
    end
    

    会很好的

    user_config :config_value => "what they want", ...
    

    推荐文章