1

When I pass the value of 75 to my program, why does it print out "no number"? 75 is less than 100 and greater than 50. It should print out "range: 50 - 100".

def report_back(value) 
case value
    when (value < 100) && (value > 50)
        message = 'number range: 50 - 100' 
    else
        message = 'no number'
end
   return message
end

puts 'enter a number between 0 - 100:'
number = gets.chomp.to_i

puts report_back(number)
David Guyon
  • 2,759
  • 1
  • 28
  • 40
DEdesigns57
  • 361
  • 1
  • 5
  • 13

3 Answers3

1

You are using the case statement incorrectly.

A more appropriate approach would be to use a range in your when or to use an if statement.

Example below.

def report_back(value) 
  case value
  when 50...100
    'number range: 50 - 100' 
  else
    'no number'
  end
end

As an aside, you also do not need a return value.

Rob Di Marco
  • 43,054
  • 9
  • 66
  • 56
1

I'm not a Ruby expert at all but based on this post, I would suggest you to write your switch statement like this:

case value
when 50..100
    message = 'number range: 50 - 100' 
else
    message = 'no number'
end
Community
  • 1
  • 1
David Guyon
  • 2,759
  • 1
  • 28
  • 40
1

Is there any reason you've chosen to structure your answer like this? You could easily write it out as something like:

def report_back(value)
  value < 100 && value > 50 ? message = 'number range: 50 - 100' : message = 'not'
  puts message
end

number = gets.chomp.to_i
report_back(75)

You generally use case when there are more than 3 options. Here, a simple if...else would probably be a better choice, since there are really only 2 options. I chose to use a ternary operator here, but the ?..: is identical to if...else.

A few technical points

  • there is no need for the return statements; Ruby has implicit return, so the return keyword isn't necessary.
  • Using puts outside of the function to return data is generally discouraged; its best to use puts inside ie: in place of the return keyword here

Hope that helps. You're off to a good start - you'll get it in no time!

Alex Yanai
  • 84
  • 4
  • # here is my new program, let me know what you think? def report_back(value) if value < 100 && value > 50 puts 'number range: 50 - 100' elsif value < 50 puts 'number range: 0 - 50' else puts 'number is bigger than 100' end end puts 'enter a number between 0 - 100:' number = gets.chomp.to_i puts report_back(number) – DEdesigns57 Feb 10 '15 at 16:10
  • Looks good! Small comment: on the last line (line 13?) you're using `puts` again, which is redundant. `puts` prints to the standard output (it'll print it out on the console) so it will print the proper result from within the method. I haven't run it, but my guess is that all that `puts` will do is add an extra line in the console output. Removing it will give you the program you want. Great improvement though! Looks like it will print what you want it to. – Alex Yanai Feb 10 '15 at 16:27