Strings v. Integers

the first bit of code does what i want it to:

loop do
move = gets.to_i

if move == 1
puts “up”
elsif move == 2
puts “left”
elsif move == 3
puts “down”
elsif move == 4
puts “right”
else puts “it didn’t work”
end
end

when i try to convert it to the keys WASD, it doesn’t work:

loop do
move = gets.to_s

if move == “w”
puts “up”
elsif move == “a”
puts “left”
elsif move == “s”
puts “down”
elsif move == “d”
puts “right”
else puts “it didn’t work”
end
end

an explanation of why would be appreciated

(also, should there be a way to get feedback from the program without
using the enter key, that would be appreciated too(ex, as soon as the
w/1 key is pressed, the program prints “up” and then loops again)

Try the following code:

loop do
move = gets.to_s
puts “Input string is:”
puts move.inspect
puts “And it is #{move.size} characters long.”
puts “Is it equal to the string “w” ?”
puts move == “w” ? “yes” : “no”
end

Now press w and observe.

After this, you should be able to understand why this modification to
your code helps:

move = gets.to_s.chomp.downcase

Check the ruby docs if you are unfamiliar with methods from the standard
library.

http://ruby-doc.org/core-2.2.0/String.html

Thankyou! this was very helpful.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs