Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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().

like image 273
Cory Regan Avatar asked Jan 27 '13 19:01

Cory Regan


People also ask

What does =~ mean in Ruby?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

How do I check if a string is in Ruby?

In Ruby, we can use the double equality sign == to check if two strings are equal or not. If they both have the same length and content, a boolean value True is returned. Otherwise, a Boolean value False is returned.

How do you access characters in a string in Ruby?

Accessing Characters Within a String You can also access a single character from the end of the string with a negative index. -1 would let you access the last character of the string, -2 would access the second-to-last, and so on. This can be useful for manipulating or transforming the characters in the string.

Is number in Ruby?

Ruby supports two types of numbers: Integers: An integer is simply a sequence of digits, e.g., 12, 100. Or in other words, numbers without decimal points are called Integers. In Ruby, Integers are object of class Fixnum(32 or 64 bits) or Bignum(used for bigger numbers).


2 Answers

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.

like image 200
Andrew Marshall Avatar answered Sep 17 '22 19:09

Andrew Marshall


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 
like image 41
PinnyM Avatar answered Sep 20 '22 19:09

PinnyM