Home > Mobile >  Create a function "Are you playing banjo?". If your name starts with the letter "R&qu
Create a function "Are you playing banjo?". If your name starts with the letter "R&qu

Time:03-24

Can anybody explain where Im going wrong using the ruby program? Im having trouble remembering how to be specific enough for the computer to understand without writing too long of a code any advice would be much appreciated?



def are_you_playing_banjo(name)
  name = 0
  i = 0
  while i <= word.length
    name  = "Are you playing banjo? "
    char = word[i] 
  if char == "r" || char == "R"
    puts true 
  elsif 
    puts false
    end
    i  = 1
    end
  return name
end

CodePudding user response:

You are doing far too much, and are making quite a lot of errors along the way. You seem to try to test every char in name for being "r" or "R", but the title says "starts with". Can you come up with a way of getting the first character of name and storing it in a variable (in your code char is used as variable, which is fine)? Your code already has a way to test if this char is an "r" or "R", which will be true or false - exactly what you want. Close with an end and you're done.

CodePudding user response:

This problem can be solved in several ways, I will give my solution as an example, but this does not mean that it is the most correct way.

First of all you don't need to use any loops here to know if name contains 'r' letter.

  1. Firstly you can remove leading and trailing whitespaces in case your name contains it, so to be sure. For this you can use strip() method.
  2. Then you can use if-else conditional statement to see if first letter of the name contains letter 'r' or not. In your problem, it doesn’t matter whether it is capitalized or not, we only care about the letter itself, so we only check this. If so - we return true otherwise false. (In my example, I store it in a variable right away in one line, it's shorter than usual if-else statement, it's called ternary operator)
  3. Then depending on what result you have, you can print and return what you want.
def are_you_playing_banjo(name)
  str = name.strip[0].upcase == 'R' ? true : false # => true
  puts str                                      # => will print *true*
  name                                        # => will return name "ruby"
end

are_you_playing_banjo('ruby') # => "ruby"

I hope this helps you a little.

  • Related