0

I have the following code to fetch the data from MySQL database into my rails controller

@main = $connection.execute("SELECT * FROM builds WHERE platform_type IS NOT NULL")

This returns a mysql2 type object which behaves like an array i guess.

I want to split this into 2 arrays, first one where platform_type is 'TOTAL' and everything else in the other array.

2 Answers 2

2

It actually returns a Mysql2::Result object. Of course you can do

totals = []
others = []
main.each { |r|
  (r['platform_type'] == 'TOTAL' ? totals : others) << r
}

but why not use a rails way with smth like:

Builds.where("platform_type = ?", 'TOTAL')
Builds.where("platform_type NOT IN ?", [nil, 'TOTAL'])
Sign up to request clarification or add additional context in comments.

2 Comments

undefined method `each_hash' for #<Mysql2::Result:0xb73e9790>
@sagarvikani Oooups, sorry, within Mysql2 the method is called each rather than each_hash. My fault.
-1

Try array.select. Something like

total = @main.select { |build| build.platform_type == 'TOTAL' }
not_total = @main.reject { |build| build.platform_type == 'TOTAL' }

http://matthewcarriere.com/2008/06/23/using-select-reject-collect-inject-and-detect/

Even better, use Enumerable.partition as per this answer: Ruby Select and Reject in one method

1 Comment

Uhmmm… Mysql::Result is not an Array descendant actually.

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.