-5

I have a function like below:

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

I'm wondering if there is a nice way to rewrite this piece. I would like to know what would be the best thing to do.

sawa
  • 165,429
  • 45
  • 277
  • 381
minu
  • 117
  • 1
  • 1
  • 6

3 Answers3

0

As far as I can see you are trying to convert an object to a Hash datastructure. Check out Ruby convert Object to Hash

Andreas Müller
  • 121
  • 1
  • 5
0

If I get the point, also as pointed by Andreas Müller, maybe the automatic method here below is what you are looking for:

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"}
iGian
  • 11,023
  • 3
  • 21
  • 36
0

In case we are not talking about (all) instance variables and the hash keys have to be camelcase:

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
periswon
  • 596
  • 5
  • 9