Neil
Neil

Reputation: 5178

Read in String From File, Split by Tab in Ruby

I am missing something obvious. I have a string that is tab separated in a text file. I read it into an argument

Here is what it looks like in the text file:

hello   world   foo bar

So each of those words has a tab between them in the text file.

I read it into a variable

line = ""
File.open("some_file", "r+") do |file|
  line = file.gets
end

Now I simply want to split up the words by the tab separation:

word1, word2, word3, word4 = line.split("\t")

However what is happening is that it is putting ALL the words in the first variable, leaving the other variables with nil

p word1
=> "hello   world   foo bar"

p word2
=> nil

p word3
=> nil

p word4
=> nil

What am I missing? A word should be within each of those variables.

Upvotes: 1

Views: 644

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52347

This is because your string does not contain "\t" in it (but rather spaces):

words = 'hello world foo bar'
words.split(' ')
#=> ["hello", "world", "foo", "bar"]

If it really would contain tabs:

"hello\tworld"

you then would indeed be able to split it as intended:

"hello\tworld".split("\t")
#=> ["hello", "world"]

Upvotes: 1

Related Questions