0

I'm writing a Ruby script that accesses a MySQL database using the Mysql2 gem.

After I get a set of results from a query, I want to examine a subset of the rows of the result set (e.g. rows 5 to 8) rather than the whole set.

I know I can do this with a while loop, something like this:

db = Mysql2::Client.new(:host => "myserver", :username => "user", :password => "pass", :database => "books")

rs = db.query "select * from bookslist"

i = 5
while i <= 8
    puts rs.entries[i]
    i += 1
end

db.close

But I'm aware this is probably not the best way to write this in Ruby. How can I make this more "idiomatic" Ruby code?

(I know my other option is to modify the query to return only the data I want. I still want to know how to do this in Ruby)

1 Answer 1

1

Ruby provides range operator in for loop, Probably you can use following code

for i in 5..8
  puts rs.entries[i]
end
Sign up to request clarification or add additional context in comments.

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.