Note that the tab-delimited text was sorted to make it easier to see.
profile.txt #LR utf-8
john m 19
micheal m 28
abbie f 31
dabid m 17
claire f 26
From the left, "Name, Gender, Year" are tab-delimited. I would like to sort them by name.
First, check how the text itself is output.
File.open("meibo.txt") do |text|
text.each_line do |line|
p line
end
end
When you expand the file with
$ ruby example.rb
"john\tm\t19\n"
"micheal\tm\t28\n"
"abbie\tf\t31\n"
"dabid\tm\t17\n"
"claire\tf\t26\n"
Since it is expressed as, make an array of each line excluding tab space and line feed code Sort and output as standard.
Put each row in the array once, like [name, gender, age]
.
profile = []
File.open("profile.txt") do |text|
text.each_line do |line|
profile << line.chomp.split("\t")
end
end
By .chomp
and tab-separated to remove \ n
at the end of each line, by .split ("\ t")
$ ruby example.rb
[["john", "m", "19"],
["micheal", "m", "28"],
["abbie", "f", "31"],
["dabid", "m", "17"],
["claire", "f", "26"]]
The array profile
was neatly[name, gender, age]
and only the necessary data was obtained.
Since ruby has a sort_by
method, use this method to sort by name.
profile_sort = profile.sort_by{|man| man[0]}
pp profile_sort
The output result is
$ ruby example.rb
[["abbie", "f", "31"],
["claire", "f", "26"],
["dabid", "m", "17"],
["john", "m", "19"],
["micheal", "m", "28"]]
And it was safely sorted in order of name.
When you reach this point, output the sorted array, redirect it, and sort it.
profile_sort.each do |text|
puts text.join("\t")
end
Concatenate the strings of the array by connecting them with \ t
. It will be tab-delimited when output with puts
.
Also, puts
will output with a line break, so bother withputs text.join ("\ t") + "\ n"
You don't have to write a line feed code.
Do this and the output will be
$ ruby example.rb
abbie f 31
claire f 26
dabid m 17
john m 19
micheal m 28
Yes, you have successfully sorted the tab-delimited files.
Recommended Posts