zaagan
12/29/2019 - 8:49 AM

Ruby Basics - Select and Reject

Ruby Basics - Select and Reject

# Example 1
prices = [2, 3, 4, 5, 6, 7, 8, 9]

newPrices = prices.select { |price| price > 5 }
p newPrices
# Output> [6, 7, 8, 9]

# Example 2
valid_colors = ["white", "black"]

cell_phones = [
  { type: "iphone", color: "white" },
  { type: "samsung", color: "indigo" },
  { type: "nexus", color: "black" },
]

# Using select
valid_cell_phones = cell_phones.select { |cell|
  valid_colors.include?(cell[:color])
}.map {
  |cell|
  cell[:type]
}
p valid_cell_phones
# Output> ["iphone", "nexus"]

# Using reject
invalid_cell_phones = cell_phones.reject { |cell|
    valid_colors.include?(cell[:color])
  }.map {
    |cell|
    cell[:type]
  }
  p invalid_cell_phones
  # Output> ["reject"]