gpt4 book ai didi

ruby - 用户输入字符串或整数

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:03 25 4
gpt4 key购买 nike

我试图查明用户输入的是字符串还是整数。如果我根据用户输入的要求输入固定值,我可以找到它。我无法上课。

这个有效:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com