我是Ruby的新学习者。我也试过
print "Enter a character "
a = gets
if (a == "b")
puts "b was pressed"
end
这也是
print "Enter a character "
a = gets.to_s
if (a == 'b')
puts "b was pressed"
end
答案 0 :(得分:2)
你错过了方法String#chomp
。更改您的代码如下:
print "Enter a character "
a = gets.chomp
if (a == "b")
puts "b was pressed"
end
现在运行你的代码:
kirti@kirti-Aspire-5733Z:~/Ruby$ ruby so.rb
Enter a character b
b was pressed
kirti@kirti-Aspire-5733Z:~/Ruby$
注意:您的代码无效,因为a = gets
实际上是将"b\n"
分配给变量a
,当然不等于"b"
。但是使用{{ 1}}会从字符串中删除#chomp
,只需从命令提示符输入并生成预期的输出。