简体   繁体   English

如何在Ruby中将Fixnum转换为Integer

[英]How to convert Fixnum to Integer in ruby

I am trying to get Integers, but i am getting 'Fixnum' values. 我正在尝试获取整数,但是我正在获取“ Fixnum”值。

For Eg: 例如:

arr = ["1", "2", "3", "4"]
arr.each do |a|
m = a.to_i
m.class.name

Result
=> Fixnum

According to the above example, how can i get Integer values? 根据以上示例,我如何获取整数值? Fixnum is a Integer only but while implementing one plugin, it will through an error like 'Please enter only integer'. Fixnum仅是一个整数,但是在实现一个插件时,它会出现类似“请仅输入整数”的错误。

In Ruby integers are either of the class Fixnum or Bignum for bigger numbers. 在Ruby中,整数是FixnumBignum类中的较大数字。 Both of them inherit from the Integer class. 它们都继承自Integer类。

So you already got an integer, no need to convert it further. 这样您已经有了一个整数,无需进一步转换。

1.class #=> Fixnum
1.class.superclass #=> Integer

To convert the array elements to integers you would do this: 要将数组元素转换为整数,可以这样做:

arr = ["1", "2", "3", "4"]
arr.map(&:to_i) #=> [1, 2, 3, 4]

Fixnum is the ruby class for standard integers. Fixnum是标准整数的ruby类。

Well to be specific, the Integer class covers both Fixnum s and Bignum s, but in all honesty there's nothing to done here. 具体来说,Integer类同时涵盖FixnumBignum ,但是Bignum ,这里没有任何事情要做。

All Fixnum (s) are already Integer . 所有Fixnum已经是Integer Here is some sample: 这是一些示例:

"12".to_i.class
#=> Fixnum
"12".to_i.integer?
#=> true
"12".to_i.to_int
#=> 12

The above all is possible as- 以上都是可能的-

"12".to_i.class.superclass
#=> Integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM