Can you plz, explain to me part of this code ?

Hi,

I found this code for sorting an array :

p ["AB_1020", "AB_950", "AB_50", "1000", "570"].partition{|x| x.to_i.zero? }
      .flat_map{|x| x.sort_by {|x|x[/d+/]}.reverse}

ouptut

#⇒ ["AB_50", "AB_950", "AB_1020", "570", "1000"]

``

I know that .partition{|x| x.to_i.zero? } will create an array of arrays :

[[“AB_1020”, “AB_950”, “AB_50”], [“1000”, “570”]]

But this part .flat_map{|x| x.sort_by {|x|x[/d+/]}.reverse}

I could understand it.

Thanks.

Hi,

I found this code for sorting an array :

p ["AB_1020", "AB_950", "AB_50", "1000", "570"].partition{|x| x.to_i.zero? }
      .flat_map{|x| x.sort_by {|x|x[/d+/]}.reverse}
ouptut

#⇒ ["AB_50", "AB_950", "AB_1020", "570", "1000"]

I know that .partition{|x| x.to_i.zero? } will create an array of arrays :
[["AB_1020", "AB_950", "AB_50"], ["1000", "570"]]

But this part .flat_map{|x| x.sort_by {|x|x[/d+/]}.reverse}

flat_map: https://apidock.com/ruby/Enumerable/flat_map

Then that passes a block, which acts on each member of the Enumerable that called flat_map. That block sorts by the numerical value of x, then reverses.

Does that help?

Walter

But [[“AB_1020”, “AB_950”, “AB_50”], [“1000”, “570”]] has non numerical values too.

But [[“AB_1020”, “AB_950”, “AB_50”], [“1000”, “570”]] has non numerical values too.

Hi,

I found this code for sorting an array :

p [“AB_1020”, “AB_950”, “AB_50”, “1000”, “570”].partition{|x| x.to_i.zero? }

  .flat_map{|x| x.sort_by {|x|x[/d+/]}.reverse}

You’re missing that String#[] when given a Regexp returns the substring that matches that Regexp.

[1] pry(main)> [“AB_1020”, “AB_950”, “AB_50”,].map {|x| x[/\d+/]}

=> [“1020”, “950”, “50”]

[2] pry(main)> [“AB_1020”, “AB_950”, “AB_50”,].map {|x| x[/\d+/]}.sort

=> [“1020”, “50”, “950”]

[3] pry(main)> [“AB_1020”, “AB_950”, “AB_50”,].map {|x| x[/\d+/]}.sort.reverse

=> [“950”, “50”, “1020”]

[4] pry(main)> [“AB_1020”, “AB_950”, “AB_50”,].map {|x| x[/\d+/].to_i}.sort.reverse

=> [1020, 950, 50]

[5] pry(main)> [“AB_1020”, “AB_950”, “AB_50”,].sort_by {|x| x[/\d+/].to_i}

=> [“AB_50”, “AB_950”, “AB_1020”]

-Rob

​two things look suspicious:
1) /d+/​
​2) reverse

have you tried randomly rearranging your arrays first?​

​m​
any thanks,
--botp

Thank you Rob, I appreciate your help, good explanation.