Thursday, 27 October 2016

string - Extract first word from a line in a file using Ruby



How do I get the first word from each line? Thanks to help from someone on , I am working with the code below:



File.open("pastie.rb", "r") do |file|
while (line = file.gets)
next if (line[0,1] == " ")

labwords = line.split.first
print labwords.join(' ')
end
end


It extracts the first word from each line, but it has problems with spaces. I need help adjusting it. I need to use the first method, but I don't know how to use it.


Answer



Consider this:




def first_words_from_file(file_name)
lines = File.readlines(file_name).reject(&:empty?)
lines.map do |line|
line.split.first
end
end

puts first_words_from_file('pastie.rb')

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...