2

I've check to see if the program is recieving number and names and it is. I'm wondering why doesn't it print "fred" when input number is 1?

number = ARGF.read.chomp
names = %w{fred betty barney}
if number == 1
  puts names[0]
elsif number == 2
  puts names[1]
elsif number == 3
  puts name[2]
end
Kim
  • 1,764
  • 1
  • 11
  • 14
jimmyc3po
  • 471
  • 3
  • 6
  • 16

4 Answers4

4

number is likely a string here, but you are comparing it with an integer.

1 == '1' # false

try

number = ARGF.read.chomp.to_i # note the to_i here
names = %w{fred betty barney}
if number == 1
  puts names[0]
elsif number == 2
  puts names[1]
elsif number == 3
  puts names[2]
end

Also, you can use a case/when statement when you want to take a different path based on multiple values of a single variable. This is usually the cleaner way to handle this type of flow.

number = ARGF.read.chomp.to_i
names = %w{fred betty barney}

case number
when 1
  puts names[0]
when 2
  puts names[1]
when 3
  puts names[2]
end

Or in this case, the even more simple:

number = ARGF.read.chomp.to_i
names = %w{fred betty barney}
puts names[number-1]

should work.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • 1
    Using a `case` statement is better for a number of reasons: It's significantly faster to execute, it is easier to read especially when mapping several values to a singular action as no `or` is required, and it's impossible to inadvertently assign with `=` instead of comparing with `==`. You're also, worryingly, the only answer that recognized this is an array indexing problem and doesn't need that kind of logic at all. – tadman Nov 18 '11 at 19:17
  • "It's significantly faster to execute" ... [citation needed] – DGM Nov 18 '11 at 20:08
  • Not a citation, but related at least: http://stackoverflow.com/questions/4178240/which-is-faster-in-ruby-a-hash-lookup-or-a-function-with-a-case-statement – Alex Wayne Nov 18 '11 at 20:35
3

I know you're learning if...else, but keep in mind you can also do this:

number = ARGF.read.chomp.to_i - 1
names = %w{fred betty barney}

puts names[number]
clem
  • 3,524
  • 3
  • 25
  • 41
2

number is a string, not an integer. You can either convert to an integer:

number = ARGF.read.chomp.to_i

or you can test against strings instead:

if number == "1"
  ...
  ...
  ...
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • Gosh, that is killing me on almost every program I write...convert to string and integer. Regardless, thanks a lot for you response, much appreciated. – jimmyc3po Nov 18 '11 at 18:42
2

The number is a string. You can check that that by printing its class like this:

p number.class

You need to convert number to an integer like this:

number = ARGF.read.chomp.to_i

Keep in mind though that to_i would return 0 for invalid string. Do it only when you are sure about the incoming data.

Try this on Codepad.

detunized
  • 15,059
  • 3
  • 48
  • 64