【问题标题】:What are the equivalent to Lodash's get and set in Ruby?Lodash 在 Ruby 中的 get 和 set 等价物是什么?
【发布时间】:2016-02-09 14:33:54
【问题描述】:

我想使用类似于 Lodash 的 get 和 set 的东西,但使用的是 Ruby 而不是 JavaScript。我尝试了几次搜索,但找不到类似的东西。

Lodash 的文档可能会以更好的方式解释它,但它是从字符串路径获取和设置属性(例如,'x[0].y.z')。如果设置属性时完整路径不存在,则会自动创建。

【问题讨论】:

标签: ruby lodash


【解决方案1】:

我最终将 Lodash _.set 和 _.get 从 JavaScript 移植到 Ruby 和 made a Gem

【讨论】:

    【解决方案2】:

    Ruby 2.3 引入了新的安全导航运算符,用于获取嵌套/链式值:

    x[0]&.y&.z #=> result or nil
    

    否则,Rails 猴子用try(…) 修补所有对象,允许您:

    x[0].try(:y).try(:z) #=> result or nil
    

    设置有点困难,我建议在尝试设置属性之前确保您拥有最终对象,例如:

    if obj = x[0]&.y&.z
      z.name = "Dr Robot"
    end
    

    【讨论】:

    • 谢谢。在我的用例中,字符串路径是动态的,仅在运行时知道,但我将在其他地方使用安全导航运算符。
    【解决方案3】:

    您可以使用大多数 Lodash 实用程序附带的 Rudash Gem,而不仅仅是 _.get 和 _.set。

    【讨论】:

      【解决方案4】:

      有时我需要以编程方式将某个属性的值深入到对象中,但问题是有时该属性实际上是一种方法,有时它需要参数! p>

      所以我想出了这个解决方案,希望它有助于为您的问题设计一个解决方案: (需要 Rails 的#try)

      def reduce_attributes_for( object, options )
        options.reduce( {} ) do |hash, ( attribute, methods )|
          hash[attribute] = methods.reduce( object ) { |a, e| a.try!(:send, *e) }
          hash
        end
      end
      
      # Usage example
      o = Object.new
      
      attribute_map = {
          # same as o.object_id
          id: [:object_id],
          # same as o.object_id.to_s
          id_as_string: [:object_id, :to_s],
          # same as o.object_id.to_s.length
          id_as_string_length: [:object_id, :to_s, :length],
          # I know, this one is a contrived example, but its purpose is
          # to illustrate how you would call methods with parameters
          # same as o.object_id.to_s.scan(/\d/)[1].to_i
          second_number_from_id: [:object_id, :to_s, [:scan, /\d/], [:[],1], :to_i]
      }
      
      reduce_attributes_for( o, attribute_map )
      # {:id=>47295942175460,
      #  :id_as_string=>"47295942175460",
      #  :id_as_string_length=>14,
      #  :second_number_from_id=>7}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-16
        • 1970-01-01
        • 1970-01-01
        • 2010-11-23
        • 2014-12-29
        • 1970-01-01
        • 2013-03-23
        • 2011-07-23
        相关资源
        最近更新 更多