1
File.open(path, 'r').each do |line| 
  row = line.chomp.split('\t')
  puts "#{row[0]}"
end

path is the path of file having content like name, age, profession, hobby

I'm expecting output to be name only but I am getting the whole line.

Why is it so?

Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
Milan
  • 1,447
  • 5
  • 19
  • 27
  • Edit your question to include sample input and output - that will help people to answer your question. – Gishu Jul 22 '10 at 07:13

2 Answers2

5

The question already has an accepted answer, but it's worth noting what the cause of the original problem was:

This is the problem part:

split('\t')

Ruby has several forms for quoted string, which have differences, usually useful ones.

Quoting from Ruby Programming at wikibooks.org:

...double quotes are designed to interpret escaped characters such as new lines and tabs so that they appear as actual new lines and tabs when the string is rendered for the user. Single quotes, however, display the actual escape sequence, for example displaying \n instead of a new line.

Read further in the linked article to see the use of %q and %Q strings. Or Google for "ruby string delimiters", or see this SO question.

So '\t' is interpreted as "backslash+t", whereas "\t" is a tab character.

String#split will also take a Regexp, which in this case might remove the ambiguity:

split(/\t/)
Community
  • 1
  • 1
Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
  • Yep your answer is way more precise. Because the guy was talking about lines and his question was not very clear I thought that he was looking for a way to split text by lines. – BlackTea Jul 22 '10 at 16:00
0

Your question was not very clear

split("\n") - if you want to split by lines

split - if you want to split by spaces

and as I can understand, you do not need chomp, because it removes all the "\n"

BlackTea
  • 1,274
  • 15
  • 27
  • sorry sir but how to accept nd i solved my problem actully i m using split('\t') instead if ("\t") single quotes that i m using that is wrong – Milan Jul 22 '10 at 07:21
  • To accept answer, you can click on check mark on the right side of the question. To uprate answer, you can click on the triangle which is pointing upwards which also is on the right side of the answer. Good luck – BlackTea Jul 22 '10 at 07:32