0

I have an array of objects with a boolean attribute:

[#<Animal id: 1, type: "narwhal", magical: false>, #<Animal id: 2, type: "unicorn", magical: true>]

How do I create a new array with only the objects where the boolean :magical? is true?

1 Answer 1

2

Are you looking for Enumerable#select?

a = [#<Animal id: 1, type: "narwhal", magical: false>, #<Animal id: 2, type: "unicorn", magical: true>]
b = a.select(&:magical?)
b
=> [#<Animal id: 2, type: "unicorn", magical: true>]
Sign up to request clarification or add additional context in comments.

2 Comments

@CarySwoveland: I like it improves readability and makes it really obvious that it returns true/false not just a trueish or falseish value.
@spickerman, that converts the method magical? to a proc, but we haven't been told about a method by that name. Am I missing something? I'll check back in the morning.

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.