Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save staycreativedesign/4c924bc4abee3a9fa6561987262b0ca5 to your computer and use it in GitHub Desktop.
Save staycreativedesign/4c924bc4abee3a9fa6561987262b0ca5 to your computer and use it in GitHub Desktop.
why is this match getting nil?
[5] pry(main)> receipt_number = receipt["Reference Number(s)"]
=> "121961|501526|121961|501526"
[6] pry(main)> receipt_number = receipt["Reference Number(s)"].match(/"\K\d+/)
=> nil
https://rubular.com/r/ML1ypdresB9CKY
@nilbus
Copy link

nilbus commented Sep 10, 2019

[1] pry(main)> receipt_number = "121961|501526|121961|501526"
=> "121961|501526|121961|501526"
[2] pry(main)> receipt_number.match(/"\K\d+/)
=> nil
[3] pry(main)> receipt_number.match(/\A\d+/)
=> #<MatchData "121961">
[4] pry(main)> receipt_number.match(/\A\d+/)[0]
=> "121961"

A more readable regex that works if receipt_number can't have multiple lines:

[6] pry(main)> receipt_number.match(/^\d+/)[0]
=> "121961"

Another approach that's easier to read and understand but less efficient if the string could be very long (hundreds or more).

[6] pry(main)> receipt_number.split('|').first
=> "121961"

Prefer readability over efficiency when the efficiency gain isn't significant to the business goals of what you're building.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment