0

I have an array of objects

@posts = [ { 
    "post": {
              "id":33,"title":"1","body":"","created_at":"2022-01-16T16:54:11.911Z","updated_at":"2022-01-16T16:54:25.642Z","user_id":3,"archive":null,"public_id":1
              },
    "attachments":[],
    "tags": []
  },
  { 
    "post": {
              "id":33,"title":"1","body":"","created_at":"2022-01-16T16:54:11.911Z","updated_at":"2022-01-16T16:54:25.642Z","user_id":3,"archive":null,"public_id":1
              },
    "attachments":[],
    "tags": []
  },
  { 
    "post": {
              "id":33,"title":"1","body":"","created_at":"2022-01-16T16:54:11.911Z","updated_at":"2022-01-16T16:54:25.642Z","user_id":3,"archive":null,"public_id":1
              },
    "attachments":[],
    "tags": []
  },
]

I want to sort by the post.created_at column for the array collection

I have tried

render json: @posts.sort_by { |h| h.created_at.split('/').reverse }

But am getting undefined method created_at' for #<Hash`

Kyle
  • 1,153
  • 5
  • 28
  • 56
  • It looks like you're combining Ruby and JavaScript syntaxes and types. There's no dot notation for property access on Ruby hashes. E.g. https://stackoverflow.com/questions/9356704/unable-to-use-dot-syntax-for-ruby-hash – coreyward Jan 16 '22 at 17:28
  • You can use `posts.sort_by { |h| h[:created_at] }`. This works because of the format of the date string: year-month-day-hr-min-sec, etc.. For example, `"2022-01-16T16:23:11.911Z" < "2022-01-16T16:54:33.742Z" #=> true`. `<` follows from [String#<=>](https://ruby-doc.org/core-2.6.3/String.html#method-i-3C-3D-3E). Note that Ruby has `nil` but not `null`. See [NilClass](https://ruby-doc.org/core-2.7.0/NilClass.html). – Cary Swoveland Jan 16 '22 at 18:43

0 Answers0