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

标签 ruby

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

这有效:

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/

相关文章:

ruby-on-rails - postgresql 和 rails 4 的二进制文件附件 "unrecognizable format"

ruby-on-rails - Heroku Rake 任务不理解 rand 方法

ruby-on-rails - 计算 ruby​​ 中的可用周数

arrays - 通过唯一键合并 Ruby 中的两个数组

ruby-on-rails - 异常通知程序 gem 问题

ruby-on-rails - Rails Chartkick Lines 未在多系列 line_chart 中绘制

ruby - 了解语句 "rescue ErrorType1, ErrorType2 => ex"的语法

ruby-on-rails - Rails 将参数/参数传递给 ActiveRecord 回调函数

ruby-on-rails - 在 MRI 和 jruby 之间切换的 Shell 脚本

ruby-on-rails - 拯救 Rails 应用程序中的 LoadError