Issue #21932 has been updated by naruse (Yui NARUSE). Eregon (Benoit Daloze) wrote in #note-8:
I think returning 0 when the group isn't parseable as a number seems bad behavior.
At least if I would use this method, I would expect two things of it: * It returns the Integer value of that group, without needing `Integer($N)` * It fails if the capture isn't a number, like Kernel#Integer
Does anyone have a use case for returning 0 when the group isn't a number? It just seems like a "broken data" situation for no reason when e.g. using the wrong group number.
There is two reason: 1. there are two major method to parse integer in Ruby: to_i and Integer(). * to_i is loose and the default base is 10 * Integer is strict, and the default base is `0`; it interprets "0o" and "0x" prefix In this use case, interpreting "0x" prefix is not useful. If this behavior is to_i, it is easy to explain the behavior. In other words, `match_data.get_int(n)` behaves as `match_data[n]&.to_i` 2. Distinguish with the group is not matched Considering `/(a)|(\d+)/ =~ "a"; $~.get_int(2)`. The current proposal says it returns nil. Another option for this case is exception, but I think it is not useful. At this time I can distinguish the case with matching "0", because this returns 0. Other minor reasons are... * for empty string, it will returns 0. * if you want to reject non integers, you can write strict regexp pattern. ---------------------------------------- Feature #21932: `MatchData#get_int` https://bugs.ruby-lang.org/issues/21932#change-116772 * Author: nobu (Nobuyoshi Nakada) * Status: Open ---------------------------------------- This is suggested by @akr today, `$~.get_int(1)` is equivalent to `$1.to_i` but does not create the intermediate string object. https://github.com/nobu/ruby/tree/match-get_int -- https://bugs.ruby-lang.org/