getting the last word in each line

J

Joe Van Dyk

Is there a prettier way to read a file and return the last word in each line?

Here's my go:

File.read(some_file).to_a.map { |l| line.split.last }

What if I wanted to search the lines (based on a regex) and return the
last word in each line that satisfied the search criteria?

Joe
 
V

Vincent Fourmond

Hello !
File.read(some_file).to_a.map { |l| line.split.last }

What if I wanted to search the lines (based on a regex) and return the
last word in each line that satisfied the search criteria?

What about

File.read(some_file).to_a.map { |l| line.split.select {|v| v =~
/regex/}.last }

Vince
 
B

Ben Bleything

Is there a prettier way to read a file and return the last word in each
line?

Well, there's #readlines...

File.readlines('somefile').map {|f| f.split.last}

...which is a little nicer.
What if I wanted to search the lines (based on a regex) and return the
last word in each line that satisfied the search criteria?

File.readlines('somefile').map do |f|
next unless f =~ /regex/
f.split.last
end

But you'll have nils everywhere that a line was next'ed over...

File.readlines('somefile').reject{|f| f !~ /regex/}.map {|f| f.split.last}

Someone else might have an elegant solution, but these will work :)

Ben
 
N

nobu

Hi,

At Wed, 13 Sep 2006 06:57:47 +0900,
Joe Van Dyk wrote in [ruby-talk:214152]:
File.read(some_file).to_a.map { |l| line.split.last }

$ ruby -e 'p open(ARGV[0]){|f|f.grep(/(\w+)\s*$/){$1}}' version.h
["190", "20060912", "1", "9", "0", "2006", "9", "12"]
 
L

Logan Capaldo

What about

File.read(some_file).to_a.map { |l| line.split.select {|v| v =~
/regex/}.last }
That call to_a is unecessary. File.read(some_file).map { ... } will work
just as well.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top