0

hi how to count array of hash based some values in ruby?

example :

gundams = [{:type=>"perfect grade", :name=>"00 raiser gundam 1/60"}, {:type=>"perfect grade", :name=>"strike freedom gundam 1/60"}, {:type=>"perfect grade", :name=>"astray red flame gundam 1/60"}, {:type=>"master grade", :name=>"exia gundam 1/100"}, {:type=>"master grade", :name=>"wing zero costum 1/100"}]

how to count array of hash based type? i want get result like this :

{"perfect grade"=>3, "master grade"=>2}

thanks before

4 Answers 4

2

Using Enumerable#group_by:

gundams = [
  {:type=>"perfect grade", :name=>"00 raiser gundam 1/60"},
  {:type=>"perfect grade", :name=>"strike freedom gundam 1/60"},
  {:type=>"perfect grade", :name=>"astray red flame gundam 1/60"},
  {:type=>"master grade", :name=>"exia gundam 1/100"},
  {:type=>"master grade", :name=>"wing zero costum 1/100"}
]
Hash[gundams.group_by {|g| g[:type]}.map {
  |type, gs| [type, gs.size]
}]
# => {"perfect grade"=>3, "master grade"=>2}
Sign up to request clarification or add additional context in comments.

5 Comments

i mean result like this {"perfect grade"=>3, "master grade"=>2}, sorry not add string. thank you for you answer, already right :)
@tardjo, I see. I updated the answer according to the question edit.
hi @falsetru how to convert result to [3,2] ?
@tardjo, Use Hash#values: Hash[gundams.group_by {|g| g[:type]}.map { |type, gs| [type, gs.size] }].values
@tardjo, If you don't need the hash at all, just: gundams.group_by {|g| g[:type]}.map { |type, gs| gs.size }
1

As suggested by @falsetru (who was faster), use Enumerable#group_by

gundams.group_by { |e| e[:type] }.map { |k,v| [k, v.length] }
=> [["perfect grade", 3], ["master grade", 2]]

You can then print the array above as you wish.

Comments

0

Something like this?

gundams = [{:type=>"perfect grade", :name=>"00 raiser gundam 1/60"}, {:type=>"perfect grade", :name=>"strike freedom gundam 1/60"}, {:type=>"perfect grade", :name=>"astray red flame gundam 1/60"}, {:type=>"master grade", :name=>"exia gundam 1/100"}, {:type=>"master grade", :name=>"wing zero costum 1/100"}]

# Create a hash with a 0 as default value
total = Hash.new(0)

# Iterate on each value and increment for its type
gundams.each { |value| total[value[:type]] += 1 }

p total
# => {"perfect grade"=>3, "master grade"=>2}

1 Comment

hi @Martin how to convert result to array like this [3,2] ?
0

Different approach to solving the problem with Enumerable#each_with_object

gundams.each_with_object(Hash.new(0)) { |x,hash| hash[x[:type]] += 1 }
#=> {"perfect grade"=>3, "master grade"=>2}

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.