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 trial

Ruby

Jeff Lange
Jeff Lange
8,788 Points

Can'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

  1. ask the user to input the value of the variable "a"
  2. 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
Joseph Kato
35,340 Points

Hi 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
Jeff Lange
8,788 Points

so 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
Joseph Kato
35,340 Points

Either of these should work:

a = gets.to_i

Or change your comparison to:

a == '1'
Jeff Lange
Jeff Lange
8,788 Points

Perfect! 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!