I have an array of arrays. The first field of each contained array is a
date.
No. It's a String.
The second field of each contained array is the corresponding day
of the week. I thought that it would be very easy to sort the outer
array on the dates like this:
myArray=[["2013/09/09","Mon"],["2013/09/14","Fri"],["2013/09/11","Wed"]]
myArray.sort {|x,y| x[0] <=> y[0]}
puts(myArray.inspect)
It's not working for me. Can someone please tell me what I'm missing?
Thanks for any help.
Apart from using sort! you can use sort_by!
irb(main):012:0> a =
[["2013/09/09","Mon"],["2013/09/14","Fri"],["2013/09/11","Wed"]]
=> [["2013/09/09", "Mon"], ["2013/09/14", "Fri"], ["2013/09/11", "Wed"]]
irb(main):013:0> a.sort_by! {|x| Date.parse(x[0])}
=> [["2013/09/09", "Mon"], ["2013/09/11", "Wed"], ["2013/09/14", "Fri"]]
irb(main):014:0> a
=> [["2013/09/09", "Mon"], ["2013/09/11", "Wed"], ["2013/09/14", "Fri"]]
But I'd rather make Date elements part of the Array. Then you have
the proper representation of the data. String is just for input and
output.
Kind regards
robert
···
On Sun, Sep 22, 2013 at 8:51 PM, Doug Jolley <lists@ruby-forum.com> wrote:
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/