-4

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

1 回答 1

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"。但是使用#chomp\n从字符串中删除,您只需从命令提示符输入并产生预期的输出。

于 2013-10-06T18:12:57.650 回答