Programing

변수가 정수인지 확인

crosscheck 2020. 6. 28. 18:33
반응형

변수가 정수인지 확인


Rails 3 또는 Ruby에는 변수가 정수인지 확인하는 기본 제공 방법이 있습니까?

예를 들어

1.is_an_int #=> true
"dadadad@asdasd.net".is_an_int #=> false?

당신은 is_a?방법을 사용할 수 있습니다

>> 1.is_a? Integer
=> true
>> "dadadad@asdasd.net".is_a? Integer
=> false
>>

당신은 객체가 있는지 여부를 알고 싶은 경우에 Integer 의미있는 정수로 변환 할 수 있습니다 또는 뭔가 (같은 것들을 포함하지 "hello"하는 to_i에 변환됩니다 0)

result = Integer(obj) rescue false

문자열에 정규식을 사용하십시오.

def is_numeric?(obj) 
   obj.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
end

변수가 특정 유형인지 확인하려면 kind_of?다음을 사용하면됩니다 .

1.kind_of? Integer #true
(1.5).kind_of? Float #true
is_numeric? "545"  #true
is_numeric? "2aa"  #false

변수 유형이 확실하지 않은 경우 (숫자 문자열 일 수 있음) 매개 변수에 전달 된 신용 카드 번호라고 말하면 원래 문자열이지만 문자열이 아닌지 확인하려는 경우 t 안에 문자가 있으면이 방법을 사용합니다.

    def is_number?(obj)
        obj.to_s == obj.to_i.to_s
    end

    is_number? "123fh" # false
    is_number? "12345" # true

@Benny는이 방법에 대한 감독을 지적합니다.

is_number? "01" # false. oops!

있습니다 var.is_a? Class(귀하의 경우 :) var.is_a? Integer; 청구서에 맞을 수도 있습니다. 또는 Integer(var)구문 분석 할 수없는 경우 예외가 발생하는 곳이 있습니다.


triple equal을 사용할 수 있습니다.

if Integer === 21 
    puts "21 is Integer"
end

더 "오리지널 타이핑"방법은 respond_to?이 방법으로 "정수 유사"또는 "문자열 유사"클래스를 사용할 수 있습니다.

if(s.respond_to?(:match) && s.match(".com")){
  puts "It's a .com"
else
  puts "It's not"
end

경우 당신은 내가 방법을 찾아, 0 값을 변환 할 필요가 없습니다 to_i그리고 to_f그들 중 제로 값 (있는 경우 전환 또는 0이 아닌) 또는 실제 문자열로 변환하기 때문에 매우 유용하게 Integer또는 Float값입니다.

"0014.56".to_i # => 14
"0014.56".to_f # => 14.56
"0.0".to_f # => 0.0
"not_an_int".to_f # 0
"not_a_float".to_f # 0.0

"0014.56".to_f ? "I'm a float" : "I'm not a float or the 0.0 float" 
# => I'm a float
"not a float" ? "I'm a float" : "I'm not a float or the 0.0 float" 
# => "I'm not a float or the 0.0 float"

EDIT2 : 조심하십시오. 0정수 값이 거짓이 아닙니다. 정확합니다 ( !!0 #=> true) (@prettycoder 덕분에)

편집하다

Ah just found out about the dark cases... seems to only happen if the number is in first position though

"12blah".to_i => 12

To capitalize on the answer of Alex D, using refinements:

module CoreExtensions
  module Integerable
    refine String do
      def integer?
        Integer(self)
      rescue ArgumentError
        false
      else
        true
      end
    end
  end
end

Later, in you class:

require 'core_ext/string/integerable'

class MyClass
  using CoreExtensions::Integerable

  def method
    'my_string'.integer?
  end
end

I have had a similar issue before trying to determine if something is a string or any sort of number whatsoever. I have tried using a regular expression, but that is not reliable for my use case. Instead, you can check the variable's class to see if it is a descendant of the Numeric class.

if column.class < Numeric
  number_to_currency(column)
else
  column.html_safe
end

In this situation, you could also substitute for any of the Numeric descendants: BigDecimal, Date::Infinity, Integer, Fixnum, Float, Bignum, Rational, Complex


Probably you are looking for something like this:

Accept "2.0 or 2.0 as an INT but reject 2.1 and "2.1"

num = 2.0

if num.is_a? String num = Float(num) rescue false end

new_num = Integer(num) rescue false

puts num

puts new_num

puts num == new_num

참고URL : https://stackoverflow.com/questions/4589968/checking-if-a-variable-is-an-integer

반응형