1

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.

3
  • 1
    instead test["city"] use test[:city]. Commented May 6, 2014 at 8:17
  • Thanks but that doesn't work either. I am still getting the same error. Commented May 6, 2014 at 8:20
  • 1
    What @Monk_Code said is true, you changed the keys from Symbol to String. Also, your new method returns the value of @content[41..46].strip.to_i (the last value of the method), whereas your old method returns the entire Hash. That could cause issues as well. Since your attributes returns a Fixnum, you might get NoMethodError: undefined method 'stringify_keys' for Fixnum because of it. Fix by return test or just test on the last line of your method. Commented May 6, 2014 at 8:20

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Wow thanks, calling test on the last line fixed this after already changing the keys from a string back to a symbol, as stated by @Monk_Code and @Daniël Knippers. Could you explain why calling test again is required for it to work?
@RobinvanDijk test at last is same as return test, ruby will return last evaluated expression.
1

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.