Created
August 17, 2017 02:29
-
-
Save jcoyne/0f2fa3b34136c4d9af7172026796de53 to your computer and use it in GitHub Desktop.
Ruby confusion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby's String#gsub can take a block argument. | |
'foo'.gsub(/f(.)/) { Regexp.last_match[1] } | |
=> "oo" | |
# Here's a method that takes a block argument and passes it to String#gsub | |
def do_thing(&block) | |
'foo'.gsub(/f(.)/, &block) | |
end | |
# Here you can see that it works. | |
do_thing { 'hey' } | |
# => "heyo" | |
# But it doesn't work when we try to use Regexp.last_match :( | |
do_thing { Regexp.last_match[1] } | |
NoMethodError: undefined method `[]' for nil:NilClass | |
from (irb):11:in `block in irb_binding' | |
from (irb):8:in `gsub' | |
from (irb):8:in `do_thing' | |
from (irb):11 | |
from /Users/jcoyne/.rbenv/versions/2.4.1/bin/irb:11:in `<main>' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment