Ruby: How to find out if a character is a letter or a digit?

前端 未结 3 695
伪装坚强ぢ
伪装坚强ぢ 2021-02-05 05:15

I just started tinkering with Ruby earlier this week and I\'ve run into something that I don\'t quite know how to code. I\'m converting a scanner that was written in Java into R

相关标签:
3条回答
  • 2021-02-05 05:28

    The simplest way would be to use a Regular Expression:

    def numeric?(lookAhead)
      lookAhead =~ /[0-9]/
    end
    
    def letter?(lookAhead)
      lookAhead =~ /[A-Za-z]/
    end
    
    0 讨论(0)
  • 2021-02-05 05:28

    Regular expression is an overkill here, it's much more expensive in terms of performance. If you just need a check is character a digit or not there is a simpler way:

    def is_digit?(s)
      code = s.ord
      # 48 is ASCII code of 0
      # 57 is ASCII code of 9
      48 <= code && code <= 57
    end
    
    is_digit?("2")
    => true
    
    is_digit?("0")
    => true
    
    is_digit?("9")
    => true
    
    is_digit?("/")
    => false
    
    is_digit?("d")
    => false
    
    0 讨论(0)
  • 2021-02-05 05:33

    Use a regular expression that matches letters & digits:

    def letter?(lookAhead)
      lookAhead.match?(/[[:alpha:]]/)
    end
    
    def numeric?(lookAhead)
      lookAhead.match?(/[[:digit:]]/)
    end
    

    These are called POSIX bracket expressions, and the advantage of them is that unicode characters under the given category will match. For example:

    'ñ'.match?(/[A-Za-z]/)     #=> false
    'ñ'.match?(/\w/)           #=> false
    'ñ'.match?(/[[:alpha:]]/)  #=> true
    

    You can read more in Ruby’s docs for regular expressions.

    0 讨论(0)
提交回复
热议问题