Bradley S. wrote in post #1003497:
Thats brilliant, and very powerful.
Yes. You could also do the sorting using sort():
choices = %w[
test1_banana
test2_hamster
test9_apple
test10_egg
test4_jam
test11_cheese
]
results = choices.sort do |a, b|
a.match(/\d+/)[0].to_i <=> b.match(/\d+/)[0].to_i
end
p results
–output:–
[“test1_banana”, “test2_hamster”, “test4_jam”, “test9_apple”,
“test10_egg”, “test11_cheese”]
However, sorting requires comparing each item several times with other
items. As the calculation specified in the sort() block gets more
complex–in this case the regex matching and the to_i()'ing–it takes
more time to execute, and doing that calculation many times for the same
item becomes too costly. That is where sort_by() enters the picture.
Here are the steps sort_by goes through:
-
choices = %w[
test1_banana
test2_hamster
test9_apple
test10_egg
test4_jam
test11_cheese
]
arr = choices.map do |word|
md = word.match(/\d+/)
[md[0].to_i, word]
end
–output:–
[[1, “test1_banana”], [2, “test2_hamster”], [9, “test9_apple”], [10,
“test10_egg”], [4, “test4_jam”], [11, “test11_cheese”]]
-
sorted = arr.sort do |a, b|
a.first <=> b.first
end
p sorted
–output:–
[[1, “test1_banana”], [2, “test2_hamster”], [4, “test4_jam”], [9,
“test9_apple”], [10, “test10_egg”], [11, “test11_cheese”]]
-
results = sorted.map do |arr|
arr.last
end
p results
–output:–
[“test1_banana”, “test2_hamster”, “test4_jam”, “test9_apple”,
“test10_egg”, “test11_cheese”]
Note that when sorting, a given item still needs to be compared to other
items multiple times, but the complex calculation is only done once for
each item, with the result of the complex calculation stored as the
first element of the sub-array. The comparisons are then done without
having to do the complex calculation ever again–no matter how many
times an item is compared to another item.
As you know I’m a newbie to Ruby, but I really enjoy programming, and I
suppose tricks like the above get learned with time and experience.
Yes, the steps taken by sort_by() are a famous idiom in computer
programming for making sorting more efficient.
Can you recommend me any sources which can enhance my programming with
Ruby. So far I have completed all the exercises in Chris P.'s, Learn
to Program book and have now started reading the Pickaxe, can you
recommend anything else?
Read these forums and try to answer as many of the questions as you can
without looking at other people’s answers.
Thank you for your replies, and of course, for someone like me, its an
honour to learn from someone with your capabilities.
Thanks for the compliment, but I feel like a beginner myself!