1

I have this array right here and I need to get the "id" of each object

[{ id: 1, points: 60 }, { id: 2, points: 20 }, { id: 3, points: 95 }, { id: 4, points: 75 }]
        customers = [{ id: 1, points: 90 }, { id: 2, points: 20 }, { id: 3, points: 70 }, { id: 4, points: 40 }, { id: 5, points: 60 }, { id: 6, points: 10}]

I know how to go through the whole array with

@scores.each_with_index{ |score, index| }

However, I haven't found a way to get the objects's points.

5 Answers 5

3

Perhaps you are looking for the following.

customers = [
  { id: 1, points: 90 }, { id: 2, points: 20 },
  { id: 3, points: 70 }, { id: 4, points: 40 },
  { id: 5, points: 60 }, { id: 6, points: 10}
]
h = customers.each_with_object({}) do |g,h|
  id, points = g.values_at(:id, :points)
  h[id] = points
end
  #=> {1=>90, 2=>20, 3=>70, 4=>40, 5=>60, 6=>10}

This allows you to easily extract information of interest, such as the following.

h.keys
  #=> [1, 2, 3, 4, 5, 6] 
h.values
  #=> [90, 20, 70, 40, 60, 10] 
h[2]
  #=> 20
h.key?(5)
  #=> true 
h.key?(7)
  #=> false 
h.value?(70)
  #=> true 
h.value?(30)
  #=> false 
Sign up to request clarification or add additional context in comments.

Comments

1

What you called score is actually an hash like { id: 1, points: 60 } and I'm going to call it item

So, let's try

@scores.each_with_index do |item, index|
  puts "#{index + 1}: id #{item[:id]}, points #{item[:points]}"
end

Comments

1

So, I have this array right here and I need to get the id of each object

In order to transform each element of a collection, you can use Enumerable#map (or in this case more precisely Array#map):

customers.map { _1[:id] }
#=> [1, 2, 3, 4, 5, 6]

1 Comment

Jörg neglected to mention that numbered block parameters was introduced in Ruby v2.7. I suppose beauty is in the eye of the beholder, but to me that looks like it was whupped with an ugly stick. (Credit to Bo Diddley (at 2:51).)
1

This given construct is an array of objects so we need to individually iterate through each element and print out the value present in the objects. The following code shows how we can do it:

customers.each{|obj| p obj[:id].to_s+" "+ obj[:points].to_s }

Here we iterate through each element and print out individual entities of the hash using the obj[:id]/obj[:points] (obj being each individual object here.)

Comments

0

What about something like this?

customers.map(&:to_proc).map{ |p| [:id, :points].map(&p) }
=> [[1, 90], [2, 20], [3, 70], [4, 40], [5, 60], [6, 10]]

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.