Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I symbolize keys?

1) I am grabbing some records for the DB in HAML to display, and the attributes method on each row returns a hash. The hash's keys are strings. Should I turn those keys into symbols? I am not sure the call to symbolize_keys is worth it. I.e.,

%td #{app['comment']}

or

%td #{app[:comment]

2) I am trying to symbolize the array of hashes I return, but it is not working:

rows = Comment.all(:order => 'created DESC')
result = rows.each_with_object([]) do |row, comments|
   comments << row.attributes.symbolize_keys
end

Is it not actually pushing the symbolized hash into the comments array? I also tried symbolize_keys!, and that did not help. What am I doing wrong?

like image 305
lostintranslation Avatar asked Feb 21 '26 07:02

lostintranslation


1 Answers

Since you're using Rails, you have access to HashWithIndifferentAccess so you can bypass your "strings or symbols" issue quite easily by allow both:

h = HashWithIndifferentAccess.new(some_model.attributes)
puts h['id'] # Gives you some_model.id
puts h[:id]  # Also gives you some_model.id

Your each_with_object approach:

result = rows.each_with_object([]) do |row, comments|
  comments << row.attributes.symbolize_keys
end

should work fine so I think your problem with that lies elsewhere.

like image 144
mu is too short Avatar answered Feb 23 '26 20:02

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!