我试图找出用户输入的是字符串还是整数。如果我根据用户输入的要求输入固定值,我可以找到它。我无法获取它的类。
这有效:
name = 5
type = name.class
这不起作用:
print "Enter the value to findout its class "
name = gets
type = name.class
if type == String
puts "this is a string"
elsif type == Fixnum
puts "this is a fixnum"
else
puts "this is unknown type"
end
最佳答案
我想我要问你的问题是用户如何输入字符串?
如果用户输入:
10 #=> Fixnum
1_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000 #=> Bignum
1.0 #=> Float
"hello" #=> String
'hello' #=> String
然后你可以这样做:
def test_input
input = gets.chomp
puts eval(input).class
rescue NameError
puts "Unknown Input Class"
end
这实际上应该适用于所有定义的对象,所以如果您只想捕获您提到的那四个对象:
def test_input
input = gets.chomp
klass = eval(input).class
raise NameError unless [Fixnum, Bignum, Float, String].include?(klass)
puts klass
rescue NameError
puts "Unknown Input Class"
end
编辑:
为了规避使用直接用户输入的 eval(这是一个漏洞),Gumbo 建议改用解析器。
$ gem install parser
#!/usr/bin/ruby
require 'parser/current'
def test_input
input = Parser::CurrentRuby.parse(gets.chomp)
puts case input.type
when :str then "String"
when :float then "Float"
when :int
eval(input.to_sexp.slice(/\d+/)).class
# Yes using eval again to get Fixnum vs Bignum, but this time
# we know what the input will be, and that's ok to eval
else
"Unknown Input Class"
end
end
关于ruby - 用户输入字符串或整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23423197/