【问题标题】:How to re-factor this snippet如何重构此代码段
【发布时间】:2019-06-07 15:42:42
【问题描述】:

我有如下功能:

def test
    {
      testId: self.test_id,
      testTime: self.test_time,
      testType: self.test_type,
      city: self.city
      ......... many such variables 
     }
end

我想知道是否有一个很好的方法来重写这篇文章。我想知道最好的办法是什么。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    据我所知,您正在尝试将对象转换为 Hash 数据结构。 查看Ruby convert Object to Hash

    【讨论】:

      【解决方案2】:

      如果我明白了这一点,正如 Andreas Müller 所指出的那样,也许下面的 automatic 方法就是您正在寻找的:

      class Whathever
        attr_accessor :test_id, :test_time, :test_type, :city
      
        def initialize(*args)
          @test_id, @test_time, @test_type, @city = args
        end
      
        def manual
            {
              test_id: @test_id,
              test_time: @test_time,
              test_type: @test_type,
              city: @city
             }
        end
      
        def automatic
          self.instance_variables.each_with_object({}) { |v, h| h[v[1..-1].to_sym] = instance_variable_get(v) }
        end
      end
      
      whathever = Whathever.new('ID', 'TIME', 'TYPE', 'CITY')
      whathever.manual
      whathever.automatic
      #=> {:test_id=>"ID", :test_time=>"TIME", :test_type=>"TYPE", :city=>"CITY"}
      

      【讨论】:

        【解决方案3】:

        如果我们不是在谈论(所有)实例变量并且哈希键必须是驼峰式:

        require 'active_support/core_ext/string/inflections' 
        # or define your own camelize method 
        # eg. str.split('_').tap { |a| a[1..-1].map!(&:capitalize) }.join
        
        %w[test_id test_time test_type city].each_with_object({}) do |v, h| 
          h[v.camelize(:lower)] = send(v) 
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-08
          相关资源
          最近更新 更多