What could be the best way of getting the matching lines with the line numbers using Ruby's Enumerable#grep
method. (as we use -n
or --line-number
switch with grep command).
相关问题
- How to specify memcache server to Rack::Session::M
- Why am I getting a “C compiler cannot create execu
- reference to a method?
- ruby 1.9 wrong file encoding on windows
- gem cleanup shows error: Unable to uninstall bundl
相关文章
- Ruby using wrong version of openssl
- Difference between Thread#run and Thread#wakeup?
- how to call a active record named scope with a str
- “No explicit conversion of Symbol into String” for
- What's the difference between grep -r and -R
- Segmentation fault with ruby 2.0.0p247 leading to
- How to detect if an element exists in Watir
- uninitialized constant Mysql2::Client::SECURE_CONN
Another suggestion:
lines.find_index{ |l| l=~ regex }
.To mash up the Tin Man's and ghostdog74's answers
Enumerable#grep doesn't let you do that, at least by default. Instead, I came up with:
This isn't elegant or efficient, but why not just number the lines before grepping?
A modification to the solution given by the Tin Man. This snippet will return a hash having line numbers as keys, and matching lines as values. This one also works in ruby 1.8.7.