1

I have an multidimensional array in my ruby which looks like this :

arr= [{"10.0.1.50", "4"},
      {"10.0.1.51", "10"},
      {"10.0.1.48", "7"}]

I want to sort it such that the result should be:

result= [{"10.0.1.51", "10"},
         {"10.0.1.50", "4"},
         {"10.0.1.48", "7"}]

I am basically sorting on the first column which is 10.0.1.X. So it is sorted based on X.

2
  • Are you sorting based on left side "10.0.1.51" or right side "10" Commented Apr 24, 2013 at 22:45
  • @garbagecollection : The first column.....I just edited the post Commented Apr 24, 2013 at 22:52

1 Answer 1

4

The syntax is not Ruby and the result is a bit ambiguous, but I guess you want something along the lines of

arr.sort_by { |(x,_)| x.split(".").map(&:to_i) }.reverse!
Sign up to request clarification or add additional context in comments.

8 Comments

This does not work as the first column (10.0.1.X) is considered as a string. Is there any way I can convert that to float? If i do (.to_f) it will convert it to 10.0 ignoring everything else after it.
@sagar: You need to specify what order it is that you want to use for sorting. I'm guessing lexicographically, interpreting the dot-separated blocks as numbers? You wouldn't have these problems if you'd represent the IP addresses as what they are, 32-bit integers
It says : undefined method `to_i' for ["10.0.1.50"]:Array
@sogar: What's arr? I'm assuming arr = [["10.0.1.50", "4"],["10.0.1.51", "10"],["10.0.1.48", "7"]]. I don't see where the ["10.0.1.50"] is coming from. Since your example code is no valid Ruby (Ruby has no syntax element of the form {a_1,a_2,...,a_n}) we can only guess.
arr_tmp = $connection.execute("select code_ver from builds;") arr = Array.new arr = arr_tmp.inject(Hash.new(0)) { |hash,element| hash[element] +=1 hash }
|

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.