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()
.
=~ 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.
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.
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With