ZK Zhao
ZK Zhao

Reputation: 21523

Ruby: turn each into collect

Each lecture has a stars representing its rating, from 1 to 5, and I want to select the sub_lectures with stars >= 5. Here is what I've done:

  sub_lectures = []
  lectures.each do |lec|
    sub_lectures << lec if lec[:stars] >= 5
  end
  @lectures = sub_lectures

But I think this is quite inelegant. I know there is a collect method, which could return array by default.

How can I use collect to simplify my code?

Upvotes: 2

Views: 44

Answers (2)

Gabriel Prado
Gabriel Prado

Reputation: 11

Solution using collect:

@lectures = lectures.collect { |lec| lec if lec[:stars] >= 5 }.compact

Without calling compact the result array would contain nil values for the lectures that does not satisfy the condition. The solution using select is the actually the best one.

Upvotes: 1

David Hoelzer
David Hoelzer

Reputation: 16331

I think you're looking for the select method.

@lectures = lectures.select {|l| l[:stars} >= 5}

Upvotes: 4

Related Questions