Marcos
Marcos

Reputation: 11

ruby - tab from row not respected

I'm reading a simple txt file very well. However i'm getting the data row with tab not respected.

Below the row in the file.

Anderson Silva    R$10 off R$20 of food    10.0    2          987         Fake St          Batman Inc

And below is the out line at pry.

As we can see the 987 and Fake St is together in the same row.

Anderson Silva
R$10 off R$20 of food
10.0
2
      987         Fake St
      Batman Inc

and here the simple code

line.split("\t").map do |col|
  col = col.split("\t")
  puts col
end

Upvotes: 0

Views: 53

Answers (1)

orde
orde

Reputation: 5273

I don't know if I'm understanding your question correctly, but I'd suspect that there's not actually a tab where you expect one.

def contrived_method(str)
  str.split("\t").each do |col|
    col = col.split("\t")
    puts col
  end
end

line1 = "10.0\t2\t987         Fake St"
line2 = "10.0\t2\t987\tFake St"

contrived_method(line1)
#=> 10.0
#=> 2
#=> 987         Fake St

contrived_method(line2)
#=> 10.0
#=> 2
#=> 987
#=> Fake St

For demonstration, I've reduced the size of your string to show that the String::split method will indeed split on the supplied delimiter. And--in this case--I've used eachinstead of mapbecause there's no assignment.

You'll find the inspect method valuable in this case:

line1 = "10.0\t2\t987         Fake St"

puts line1.inspect
#=> "10.0\t2\t987         Fake St"
puts line1
#=> 10.0    2       987         Fake St

Upvotes: 1

Related Questions