سؤال

I am using mysql2 in my ruby script. using this to test API responses against the mysql DB

this is a snippet of my script

test_job_by_id_5
 id = $data["jobs"]["id"][i] # example 5
 job = JobServices.job_by_id(id)
 response = @@con.query("select * from jobs where id = #{id}") #select * from jobs where id =5
 rs=response.collect #this fails
 assert_match(job[0]['title'],rs[0]['title'],"The title values are equal for #{$data["jobs"]["id"][i]}")
end

So when i use this with ruby 1.8.7 (2011-06-30 patchlevel 352) [i686-darwin10] it works like a charm

but when i use ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux] it does not work i get this error

NoMethodError: undefined method '[]' for 
#<Enumerator: #<Mysql2::Result:0x00000012d19f18>:collect>

Can some one please help me fix this?

هل كانت مفيدة؟

المحلول

When you call collect on an Enumerable (which Mysql2::Result is), you get an Enumerator instance back. Enumerators don't implement the array access operator so you can't say enumerator[0] and get anything useful to happen; however, Enumerator does include Enumerable so they do respond to first so you probably want to do this:

rs  = response.collect
row = rs.first
assert_match(job[0]['title'], row['title'], "The title values are equal for #{$data["jobs"]["id"][i]}")

Or just skip the Enumerator entirely and call first on the response:

row = response.first
assert_match(job[0]['title'], row['title'], "The title values are equal for #{$data["jobs"]["id"][i]}")

or even this:

row = @@con.query("select * from jobs where id = #{id}").first
assert_match(job[0]['title'], row['title'], "The title values are equal for #{$data["jobs"]["id"][i]}")

Keep in mind that row.nil? will be true if your query doesn't find anything so you might want to take that into account if you don't want an exception.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top