简体   繁体   中英

Ruby: each_with_index bails when encountering Range as string, NoMethodError

I'm using the new Postgresql feature of storing an array in my Rails 4 app. As you know, each element of an array stored in PG is in strings.

So my array = [7, 8..9, 10] is what you want but is stored in PG as {'7', '8..9', '10'}. I can test for each element to turn it back into an integer or Range as needed.

But I get a NoMethodError: undefined method 'each_with_index' for "8..9":String

 array.each_with_index do |item, index|
   puts "index=#{index}, item=#{item}"
 end

The portion of my schema.rb is below:

create_table "items", force: true do |t|
  t.string   "category"
  t.string   "sub_category"
  t.string   "name"
  t.string   "explanation"
  t.integer  "scoring"
  t.integer  "high_score"
  t.boolean  "all_or_nothing"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "survey_id"
  t.boolean  "date"
  t.boolean  "time"
  t.string   "colors",         default: [], array: true
end

Running array.inspect yields:

 "[\"7\", \" 8..9\", \" 10\"]"

Reading the docs, it's not obvious to me while it's failing. It can't be for a string because it happily passed on the "7" previously. array[1].class => 'String'. My Google searches for this specific situation come up empty. I know it's a Range enclosed in a String, but at this point, it's just a string?

For completeness, it may be helpful to know that I'm using Windows and Ruby 2.0 to build this app.

Where should I look to learn how to resolve this? thanx, sam

It must be due to end of a long work day, but after a restart the next day, I cannot reproduce the behavior. It must be said that I've restarted console during this process but apparently I needed to do more to restart the entire environment in Windows. Thanks to mu is too short for hanging with me late to troubleshoot this one-off behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM