0

Attempting to learn Ruby as my first programming language. I was understanding everything fine to this point, but I am drawing a blank at this exercise and not sure where to even get started with this and could use some help.

9: Introducing || operator

Similar to the logical and operator &&, we have a logical or operator ||. The character | is located right above your enter key on the keyboard and is called a pipe. Similar to double ampersand, this one is also commonly referred to as double pipe. The || operator is used if any of the conditions can be true. For example - if number == 1 || number == 3 returns true if number is either 1 or 3. Simple right? Implement a method dinner_choice as per the instructions in the code editor.

This function should return:

  1. "steak" if celebrity is "brad pitt" or "angelina jolie"
  2. "italian" if celebrity is "ashton kutcher" or "demi moore"
  3. "french" if celebrity is none of the above

This is my attempt.

def dinner_choice(celebrity)
return "steak" if celebrity == "brad pitt" || celebrity == "angelina jolie"
return "italian" if celebrity == "ashton kutcher" || celebrity == "demi moore"
else return "french"
end

end

2 Answers2

1

You were close, this is what you want

def dinner_choice(celebrity)
  return "steak" if celebrity == "brad pitt" || celebrity == "angelina jolie"
  return "italian" if celebrity == "ashton kutcher" || celebrity == "demi moore"
  return "french"
end

You don't want the last else at the end. You can simply use return "french" because if any of the statements above it match, it won't get to that line.

Donovan
  • 15,917
  • 4
  • 22
  • 34
  • Last else is syntax error, as there is no *normal* if statement, and else doesn't work with 'value if condition' version. – Darek Nędza Dec 18 '13 at 22:37
0

The general form you're looking for is to write statements like this:

def dinner_choice celebrity
  return "steak" if celebrity == "Brad Pitt"
  return "foo" if # add programming here
end

You'll check the celebrity variable to see if it's something your method knows how to handle, and give the result that goes with the input.

The explicit return tells the Ruby interpreter to stop evaluating the rest of the code in the method and give the result specified.

You could also experiment with case statements, but IMO they're ugly and hard to maintain in most situations.

Community
  • 1
  • 1