Search code examples
ruby-on-railsrubyruby-on-rails-3.1

How to determine if the contents of a text field are a hash or a string in rails using ruby?


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!


Solution

  • You could

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

    or

    if Hash === suggestion
      # ...
    end