0

I want to return any items that are cheap, which should return any items that cost less than $300.

This is the main class;

class ShoesInventory
  def initialize(items)
    @items = items
  end

  def cheap
    # this is my solution, but it just print out an array of boolean
    @items.map { |item| item[:price] < 30 }

    # to be implemented
  end
end

This is an instance of the class ;

ShoesInventory.new([
  {price: 101.00, name: "Nike Air Force 1 Low"}},
  {price: 232.00, name: "Jordan 4 Retro"},
  {price: 230.99, name: "adidas Yeezy Boost 350 V2"},
  {price: 728.00, name: "Nike Dunk Low"}
]).cheap

I want the result to be like this;

# => [
#      {price: 101.00, name: "Nike Air Force 1 Low"}},
#      {price: 232.00, name: "Jordan 4 Retro"},
#      {price: 230.99, name: "adidas Yeezy Boost 350 V2"},
#    ]

Can you guide me ?
Stefan
  • 109,145
  • 14
  • 143
  • 218
Asyraf
  • 609
  • 6
  • 14
  • In this case you just need to replace `map` with `select` as Drenmi points out in their answer, but you might want to take a little time to browse through the [Enumerable methods](https://ruby-doc.org/core-3.0.2/Enumerable.html) since there are many useful ones in there – max pleaner Oct 08 '21 at 03:02
  • This is probably "just" an exercise but you shouldn’t use floats for monetary values. Take a look at the [Money](https://github.com/RubyMoney/money) gem for a better alternative. – Stefan Oct 08 '21 at 05:47
  • 1
    @Stefan if you're using a Ruby hash as your data storage rounding errors are probally the least of your concerns... – max Oct 08 '21 at 12:56
  • @max I just don't feel comfortable seeing a "price" of `230.990000000000009094947017729282379150390625` :-) – Stefan Oct 08 '21 at 13:14

1 Answers1

5

What you're looking for is Enumerable#select.

class ShoesInventory
  def initialize(items)
    @items = items
  end

  def cheap
    @items.select { |item| item[:price] < 30 }
  end
end

If you want to be able to chain methods, you might also want to return a new inventory instance:

def cheap
  self.class.new(@items.select { |item| item[:price] < 30 })
end
Drenmi
  • 8,492
  • 4
  • 42
  • 51
  • Thank you!!! I am new to ruby. Why do I need to use the map if I can use select straightforward? Lesson learned. After this, I need to study Enumerable more :P. – Asyraf Oct 09 '21 at 01:13
  • 1
    The Enumerable module is one of the real gems (pun intended) of the Ruby language. It's worthwhile to just read the API documentation top-to-bottom a few times. :-) – Drenmi Oct 12 '21 at 09:20