What is the cleanest thread binding method working in Ruby?

Let's say I have an array of things that I want to perform all kinds of stupid operations on. For instance:

my_array = [
  { name: 'Lyra', age: 12 },
  { name: 'Harry', age: 11 },
  { name: 'Kestrel', age: 13},
]

I want to filter out someone under the age of 12, change all the names to characters, and then sort them by age (say).

This can be achieved using

new_array = my_array.
  select { |person| person[:age] > 11 }.
  map { |person| person.merge(name: person[:name].to_sym) }.
  sort_by { |person| person[:age] }

So it's all dandy. But what if I have an arbitrarily complex logic, do I need to do a selection / matching / sorting / etc.?

Standard practice says that multi-line blocks with curly braces should be avoided (and some linters even explicitly forbid). However, an alternative is to run a block chain do..end, which looks even more unpleasant:

new_array = my_array.
  select do |person|
    # Do something complex
  end.
  map do |person|
    # More complex stuff
  end.
  sort_by do |person|
    # Yet more complex stuff
  end

Ruby - ? , Proc ( ) ?

+4
1

:

new_array = my_array.dup

new_array.select! do |person|
  # Do something complex
end

new_array.map! do |person|
  # More complex stuff
end

new_array.sort_by! do |person|
  # Yet more complex stuff
end
+4

Source: https://habr.com/ru/post/1679230/


All Articles