0

I am certain this is very simple, but I'm a noob to Ruby and can't seem to find the answer to a very basic question.

I have a table with a list of words in PostgreSQL. I am getting a return value from a query to get a count of rows. When I try to assign this returned value to a variable "wordcount," I can't seem to get just the integer value. For example, if I try to use wordcount (as obtained below), Ruby throws an error "can't convert Array into Integer (TypeError)." In short, how do I convert the value obtained from the query to an integer? Thanks in advance.

q = 'SELECT COUNT(*) FROM words'
res  = conn.exec(q)
wordcount = res.values[0]
puts wordcount

3 Answers 3

1

Using PostgreSQL (and probably most other connectors), it would be:

wordcount = res[0]["count"]

are you sure you don't want to just do:

Word.count

though?

Sign up to request clarification or add additional context in comments.

1 Comment

Yep good spot - though I actually meant res[0]["count"]. And yep that's true, but thought it might be worth a mention given the OP's self-professed noobishness!
1

The exec method returns a PGResult instance and PGResult#values:

Returns all tuples as an array of arrays.

So your res is an array of arrays: one entry for each row in the result set and each entry will itself be an array with one entry per column. They're strings as well, try this:

wordcount = res.getvalue(0, 0).to_i
puts wordcount

Comments

0

The database library is giving you a return value that supports the return of multiple rows. You are probably getting an array with a single row that contains an array with a single column that takes your value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.