0

If I have an input as below:

a b 703
o z 403
l p 550
d m 650

How can I make it to work so that the list sorts by the second column that is. The above list should print

a b 703
d m 650
l p 550
o z 403

Below is my code, what I thought was I could iterate through the first column and then sort the second column by key but it doesn't seem to be working.

hash = {}
lines = file.readlines
lines.each{|line|
 if line =~ /^([A-Za-z]+) ([A-Za-z]+) (\d+)$/
   hash[$1.to_s] = {} if hash[$1.to_s] == nil
   hash[$1.to_s][$2.to_s] = $3.to_i
 end
 }


hash.each{|k,v|
array = Hash[v.sort]
array.each{|x,y|
puts "#{k} #{x} #{y}"
 }
}

The code prints as the original one. I really want to do this using hashes as I am learning hashes.

2
  • 2
    Your example is not good because it does not make difference whether it is sorted by the first column or the second. Commented Mar 13, 2014 at 18:02
  • even for 3rd column in descending order. Commented Mar 13, 2014 at 18:29

2 Answers 2

1
lines = [
  "a b 703",
  "o z 403",
  "l p 550",
  "d m 650",
]

lines.sort_by{|l| l.scan(/\w+/)[1]}
# =>
# [
# "a b 703",
# "d m 650",
# "l p 550",
# "o z 403"
#]
Sign up to request clarification or add additional context in comments.

1 Comment

your solution is taking 2nd column in consideration. For that it is perfect.
0

As Sawa says:--

lines = [
  "a b 703",
  "o z 403",
  "l p 550",
  "d m 650",
]

case 1: sort by 1st column

lines.sort_by{|l| l.scan(/^[A-Za-z]/).first}

case 2: sort by 2nd column

lines.sort_by{|l| l.scan(/\W+[A-Za-z]/).first}

case 3: by 3rd column in descending order

lines.sort_by{|l| l.scan(/\d+$/).first.to_i}.reverse

1 Comment

there are 4 more possibilities 1) by 1st and 2nd column, 2) by 2nd and 3rd column in descending, 3) by 1st and 3rd column in descending order and 4) by all 3 columns with 3rd column in descending order. We can ignore last 3 possibilities and work on first possibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.