0

I have a field defined as text (on the database side) in my rails application. Now, some of the older data was written directly to it as string. I want to start adding hashes to it.

When I retrieve the data, I want to render it differently if it is a Hash.

Here is what I have tried and it does not work because the acts_like? method is always returning false:

if suggestion.acts_like? Hash
  suggestion.each {|attr, value| puts(helper.t attr+": "+value.to_s)}
else
  puts suggestion
end

What am I doing incorrectly? Is acts_like? even the right thing to use here?


I had tried to close out the question as I found an answer for it but it seems it did not save properly.

Here is what I ended up using:

if suggestion.is_a? Hash
....
else
...
end

I still don't know why acts_like? won't work but is_a? does work! Oldergod's suggestion of kind_of? works too!

casperOne
  • 73,706
  • 19
  • 184
  • 253
Tabrez
  • 3,424
  • 3
  • 27
  • 33
  • http://stackoverflow.com/questions/5367114/what-is-a-simple-elegant-way-in-ruby-to-tell-if-a-particular-variable-is-a-has – Tabrez Aug 09 '12 at 00:43
  • What do you mean by "adding hashes to it"? How are you planning to serialize your hashes? Converting all the existing data to your new format would be best plan. – mu is too short Aug 09 '12 at 02:05
  • @muistooshort - it is actually part of another Hash (serialize :feedback, Hash) – Tabrez Aug 09 '12 at 12:16

1 Answers1

1

You could

if suggestion.kind_of?(Hash)
  # ...
end

or

if Hash === suggestion
  # ...
end
oldergod
  • 15,033
  • 7
  • 62
  • 88
  • Yes this and is_a? both work. Any idea why acts_like? does not work? Rails documentation lists that as duck typing check method. – Tabrez Aug 09 '12 at 12:14
  • the source code shows it returns respond_to? :"acts_like_#{duck}?" so I guess the acts_like_Hash? is not defined for the hash object ? – oldergod Aug 09 '12 at 23:52