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

心不动则不痛 提交于 2020-06-24 07:09:12

问题


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 Ruby for a class assignment, and I've gotten down to this section:

if (Character.isLetter(lookAhead))
{      
    return id();
}

if (Character.isDigit(lookAhead))
{
    return number();
}

lookAhead is a single character picked out of the string (moving by one space each time it loops through) and these two methods determine if it is a character or a digit, returning the appropriate token type. I haven't been able to figure out a Ruby equivalent to Character.isLetter() and Character.isDigit().


回答1:


Use a regular expression that matches letters & digits:

def letter?(lookAhead)
  lookAhead =~ /[[:alpha:]]/
end

def numeric?(lookAhead)
  lookAhead =~ /[[: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:

'ñ' =~ /[A-Za-z]/    #=> nil
'ñ' =~ /\w/          #=> nil
'ñ' =~ /[[:alpha:]]/   #=> 0

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




回答2:


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


来源:https://stackoverflow.com/questions/14551256/ruby-how-to-find-out-if-a-character-is-a-letter-or-a-digit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!