Domanda

I am getting a stringify_keys error.

Currently I am calling the following method which works perfectly:

def attributes
  {
    city:         @content[1..20].strip,
    streetname:   @content[21..40].strip,
    house_number: @content[41..46].strip.to_i
  }
end

Now that I am refactoring my code, I need to build the hash from the ground up where the keys and values are populating the hash based on certain conditions (conditions are not written yet).

def attributes
  test = {}
  test["city"]          = @content[1..20].strip
  test["streetname"]    = @content[21..40].strip
  test["house_number"]  = @content[41..46].strip.to_i
end

Now I am getting the stringify_keys error. I checked the docs for clues on how to build a hash but there isn't anything that could help me.

Where is the problem? If you need more code, please ask.

È stato utile?

Soluzione

The key is symbol in your first piece of code, and you have to return test at last in your second piece of code.

def attributes
  test = {}
  test[:city]          = @content[1..20].strip
  test[:streetname]    = @content[21..40].strip
  test[:house_number]  = @content[41..46].strip.to_i
  test
end

Altri suggerimenti

In Rails with active support you can use symbolize_keys and stringify_keys look example:

  => hash = {"foo"  => 1, 'baz' => 13}
  => {"foo"=>1, "baz"=>13}
  => hash.symbolize_keys
  => {:foo=>1, :baz=>13}

and back:

  => hash.symbolize_keys.stringify_keys
  => {"foo"=>1, "baz"=>13}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top