Enumerable is worth your time to learn. It’s very useful to solve all business logics. Without knowing it well, you end up re implement what comes with Ruby. If you don’t know select
, you will implement a slow version of select
. Ruby 2.7 has a new method called filter_map
, without filter_map
, we would probably use select
+ map
or map
+ compact
. Yes. The built-in methods are always faster than the one we wrote.
delete_if
each
+ delete
can be replaced by delete_if
.
sort 1st element asc, 2nd element desc
array = [
[1, 2],
[3, 4],
[2, 1],
[4, 3],
]
array.sort_by { |x| x[1] }.reverse.sort_by { |x| x[0] }
or you would do
array.sort_by { |element| [element.first, -element.last] }
But it could be simpler:
array.sort_by { |(x, y)| [x, -y] }
Lazily work with large collection
File.open("a-huge-file") do |file|
file.lazy.each_slice(2000) do |lines|
# ...
end
end