-1

I want my program to read each word from the text file and then, match them with numbers by row.

For example; text file is

my name is donald knuth0

and the program should run like :

"my" => "1" , "name" => "2" , "donald" => "3" , "knuth" => "4"
tadman
  • 208,517
  • 23
  • 234
  • 262
  • Your text file contains 5 words but your output shows only 4. Was the word "is" omitted on purpose? – Stefan Dec 28 '20 at 09:00

1 Answers1

0

You could do it by lines or by words. If you want to index the words by line numbers, you could probably take a little from both options.

# Option 1: Reads file as an Array of lines, but we need to replace (gsub) the newline character at the end of each line
lines_with_newlines = File.readlines("hello.txt").map{|line| line.gsub(/\n$/,"")}

# Option 2: If you wanted to do it by words instead of lines by cleaning up some whitespace
list_of_words = File.read("hello.txt").gsub(/\n/, " ").gsub(/^\s+/,"").gsub(/\s+$/,"").split(/\s/)

# Generates a list of line numbers, starting with 1
line_numbers = (1..(lines.length + 1))

# "Zips" up the line numbers [["line 1", 1], ["line 2", 2]]
pairs = lines.zip(line_numbers)

# Converts to Array
hash = Hash[pairs]
montooner
  • 1,112
  • 4
  • 17
  • 29
  • @Stefan Good point - I added a solution based on words. If OP wants to index words by line #, they could probably piece a bit from either solution. Also I'm making certain assumptions about how they want to handle whitespacing. – montooner Dec 28 '20 at 09:10