DEdesigns57
DEdesigns57

Reputation: 361

Conditions in Ruby

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)

Upvotes: 1

Views: 61

Answers (3)

Alex Yanai
Alex Yanai

Reputation: 84

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!

Upvotes: 1

David Guyon
David Guyon

Reputation: 2889

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

Upvotes: 1

Rob Di Marco
Rob Di Marco

Reputation: 44952

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.

Upvotes: 1

Related Questions