Is it possible to sort the jobs hash below based on values such as
command, start_time and stop_time?
Ideally, sort_by would be dynamically provided and I would output the
jobs entries based on the value defined for sort_by.
--------------------------(basic_script.rb)------------------------
sort_by = “start_time” #<---- I’d like to use something like this to
define which job is listed first
sort_keys = [“start_time”, “stop_time”]
jobs.sort_by do |job|
sort_keys.map do |key|
job[key]
end
end
Note that this will only work as long as all sort_keys are present in
every job.
You might want to check the documentation for Enumerable#sort_by, but
let me document the special thing in this case as well.
sort_by’s block can return multiple values as an Array. In that case it
will first sort by the first value then by the second one and so on.
This is used in the above sample where every job is sorted by the fields
representing the sort_keys on that specific job.
If you don’t mind me asking, have you had to use this before? I
wouldnt consider myself a top notch developer but between the ruby
docs and google searches, I would have never figured this out…
Any tips out how you did? Just… development experience? Thanks again!!
jobs.sort{|a,b|a[1][sort_by] <=> b[1][sort_by]}.each do |k, attributes|
I just can’t quite understand the [sort_by] usage here…?
It looks up the value in the hash from a[1] (a[0] is “2231” / “1131” /
“231” for the sample data) that represents to the key identified by
sort_by.
So if sort_by is “command” it will sort the jobs by the value
corresponding to their “command” key. Which is “test_a.bash” for job
“2231”, “test_b.bash” for job “1131”, “test_c.bash” for job “231” and so
on…
I tried adding your suggestions but ended up with an error:
ruby array_test.rb
array_test.rb:19:in []': cannot convert String into Integer (TypeError) from array_test.rb:19 from array_test.rb:18:inmap’
from array_test.rb:18
from array_test.rb:17:in sort_by' from array_test.rb:17:ineach’
from array_test.rb:17:in `sort_by’
from array_test.rb:17
Exit code: 1
for sort, ruby converts a hash to an array as hashes are not orderable
(is that a word??). Therefore accessing what seems to be a hash like an
array is in fact ok as it really is an array.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.