0
votes

I'm trying to extract data from database and use it with a pie-chart for example.

I was able to extract data from the column "browser" from the database which is a string and has this format : "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"

When I use the method "count" in my query, data will be saved as a hash like this :

{"Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"=>5, "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:51.0) Gecko/20100101 Firefox/51.0"=>9}

I'd like to show only the version of the browser or the OS for example. Is there any method (split or substring) to have a hash like this ?? and of course the method "count" should be working

{"Firefox/45.0"=>5, "Firefox/51.0"=>9}

I tried to use split but when using the method count, there will be no data found since it's saved in the database as a whole string "Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0". there is no "Firefox/45.0" in the column browser in my table in the database.

I tried also to use substring in mysql query when using a simple query from console I get the results I want but since I'm using Ruby on Rails and ActiveRecords the "substring" is not returning the same result (not working properly)

Any help please?

1
Please show the code you are using to generate your query. - moveson

1 Answers

0
votes

Do the following:

input = {"Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Firefox/45.0"=>5, "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:51.0) Gecko/20100101 Firefox/51.0"=>9}
result = {}
input.each { |k, v| result[k.split.last] = v }

Replace the input with your actual query.

What it does is that it:

  • iterates on each element of the input
  • For each one, use the key as k and the value as v,
  • Take k, split it (cut the string into words separated by spaces), and keep the last word using last
  • Add to result a new entry where the key is the last word selected, and the value is v.