I will write about the sorting of hashes contained in the array. Suppose you have a hash in an array like this:
array = [
  {
    :nickname  =>  "Mr. A",
    :image  =>  "default_user_image.jpeg ",
    :sum_size  =>  211.0,
    :max_size  =>  64.0
  },
  {
    :nickname  =>  "Mr. B",
    :image  =>  "/uploads/user/image/10/C2513F3.jpeg ",
    :sum_size  =>  215.0,
    :max_size  =>  50.0
  },
  {
    :nickname  =>  "Mr. C",
    :image  =>  "/uploads/user/image/6/FB6D582.jpeg ",
    :sum_size  =>  65.0,
    :max_size  =>  65.0
  }
]
When you want to sort in descending order of the value of : max_size.
sort_maxsize = array.sort_by! { |x| x[:max_size] }
sort_maxsize.reverse!
Execution result
  {
    :nickname  =>  "Mr. C",
    :image  =>  "/uploads/user/image/6/FB6D582.jpeg ",
    :sum_size  =>  65.0,
    :max_size  =>  65.0
  },
  {
    :nickname  =>  "Mr. A",
    :image  =>  "default_user_image.jpeg ",
    :sum_size  =>  211.0,
    :max_size  =>  64.0
  },
  {
    :nickname  =>  "Mr. B",
    :image  =>  "/uploads/user/image/10/C2513F3.jpeg ",
    :sum_size  =>  215.0,
    :max_size  =>  50.0
  }
]
I was able to sort well for : max_size!
I told you in the comments, so I will add it! !!
In the case like this time, sign inversion seems to be smart even if you do not invert after arranging in ascending order!
sort_maxsize = array.sort_by! { |x| -x[:max_size] }
Thank you for your comment!
Ruby Reference Array # reverse
Recommended Posts