Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJeff Lange
8,788 PointsCan't get an if block to work properly in Ruby
I'm a Ruby newb, and I started messing around writing some code just to see what I could figure out so far.
I wrote some code that would
- ask the user to input the value of the variable "a"
- react based on what the user inputs
Here's the code:
class IdentifyA
def initialize(name)
end
def ask
print "What is the value of a? "
a = gets.chomp
if a == 1
print "a is 1. "
elsif a == 2
print "a is 2. "
else
print "I don't know that number, dude."
end
end
end
identify_a = IdentifyA.new("name")
identify_a.class # => IdentifyA
identify_a.ask
When I run the program in the console it asks the question properly, but even if I enter 1 or 2, it still returns "I don't know that number dude."
What do I need to change?
2 Answers
Joseph Kato
35,340 PointsHi Jeff,
I think the issue is that you're comparing different data types; a
is a string, but it's being compared to integers.
Jeff Lange
8,788 PointsPerfect! That worked.
I had to look up the .to_i method for it to make sense, and found that .to_f would work as well. Either way, as you were saying, I needed to let my program know it was looking for a numerical value rather than a string, and that method is what made it work.
Thank you again!
Jeff Lange
8,788 PointsJeff Lange
8,788 Pointsso is the issue with "gets" then? Is there some other command I can use that looks for the input to be an integer rather than a string? I assumed "gets" was good good for either values or strings.
Joseph Kato
35,340 PointsJoseph Kato
35,340 PointsEither of these should work:
a = gets.to_i
Or change your comparison to:
a == '1'