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
1
  • looks like number is a string, shouldn't the comparisons be like "1", "2" and "3" ? Commented Nov 18, 2011 at 18:41

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
"It's significantly faster to execute" ... [citation needed]
Not a citation, but related at least: stackoverflow.com/questions/4178240/…
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]

Comments

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"
  ...
  ...
  ...

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.