print“输入一个字符”a =获取如果(a =='b')将“b被按下”结束

时间:2013-10-06 18:06:12

标签: ruby if-statement compare character string-comparison

我是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

1 个答案:

答案 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,只需从命令提示符输入并生成预期的输出。