Colin Marshall
Colin Marshall

Reputation: 115

Programming a basic conditional method in ruby

Create a mothod that takes two arguments.. The first argument represents what the user wants to buy (either a "computer" or "iPad"). The second argument represents how much money the user has. The method should evaluate if the user has enough money to buy a computer or an iPad. If the user has enough money for a computer or an iPad, the method should return true, otherwise it should return false.

This is what I have so far, but it's not returning right whenever I run it with sample arguments.

def can_i_get?(item,money)
  if item=="computer" 
    if money >= 1000
      return true
    end

  elsif item=="iPad"
    if money >= 500
      return true
    end

  else
    return false
  end

end

Upvotes: 1

Views: 64

Answers (4)

moveson
moveson

Reputation: 5213

There is no need to use return in Ruby, as the method automatically returns the last item evaluated.

I would define your items and costs in a Hash and reference that from within your method:

PRICE_LIST = {'computer' => 1000, 'iPad' => 500}

def can_i_get?(item, money)
  money >= PRICE_LIST.fetch(item, Float::INFINITY)
end

This is both readable and extensible--you can add items and costs to PRICE_LIST and the method will work for the new items.

By using Hash#fetch, we get back the default value (the second argument) if the item is not found within the PRICE_LIST. Returning Float::INFINITY ensures that an unknown item will evaluate to false.

Upvotes: 1

Albert Hu
Albert Hu

Reputation: 42

I like Yu Hao's answer because it solves the nil problem you may be having. I would just add that you could also use a dictionary for efficiency, in case you want to add more items to check in the future, and remove some duplicate code.

def can_i_get?(item,money)

  item_cost = {
    "computer" => 1000,
    "iPad" => 500
  }

  item_cost.key?(item) && money >= item_cost[item]
end

Upvotes: 0

spickermann
spickermann

Reputation: 106802

You can replace the method body with this condition:

def can_i_get?(item, money)
  item == 'computer' && money >= 1000 || item == 'iPad' && money >= 500
end

No need for if ... elsif ... else or a return.

Upvotes: 1

Yu Hao
Yu Hao

Reputation: 122383

What if item is computer and money is less than 500? There's nothing to catch conditions like this, so the method returns nil.

Instead, make the return false a catch-all:

def can_i_get?(item,money)
  if item=="computer" 
    if money >= 1000
      return true
    end
  elsif item=="iPad"
    if money >= 500
      return true
    end
  end
  return false
end

Upvotes: 3

Related Questions