Can you identify a block with a ruby ​​line?

Is it possible to define a block in a string expression with ruby? Something like that:

tasks.collect(&:title).to_block{|arr| "#{arr.slice(0, arr.length - 1).join(", ")} and #{arr.last}" }

Instead of this:

titles = tasks.collect(&:title)
"#{titles.slice(0, titles.length - 1).join(", ")} and #{titles.last}"

If you said tasks.collect(&:title).slice(0, this.length-1), how can you make 'this' a reference to the full array passed to slice ()?

Basically, I'm just looking for a way to pass an object returned from one statement to another, without necessarily iterating it.

+3
source share
4 answers

You confuse passing the return value to the method / function and calling the method for the return value. The way to do what you described is as follows:

lambda {|arr| "#{arr.slice(0, arr.length - 1).join(", ")} and #{arr.last}"}.call(tasks.collect(&:title))

If you want to do it the way you tried, the closest match is instance_eval, which allows you to run the block in the context of the object. So this will be:

tasks.collect(&:title).instance_eval {"#{slice(0, length - 1).join(", ")} and #{last}"}

, , , .

+4

, , :

tasks.collect(&: )?.slice(0, this.length-1), 'this' , ()

:

tasks.collect(&:title)[0..-2]

, :

"#{titles.slice(0, titles.length - 1).join(", ")} and #{titles.last}"

- , .

+1

, , ruby, , ...

class Object
  def to_block
    yield self
  end
end

:

tasks.collect(&:title).to_block{|it| it.slice(0, it.length-1)}

, Object , .

+1

, , , :

class Array
  def andjoin(separator = ', ', word = ' and ')
    case (length)
    when 0
      ''
    when 1
      last.to_s
    when 2
      join(word)
    else
      slice(0, length - 1).join(separator) + word + last.to_s
    end
  end
end

puts %w[ think feel enjoy ].andjoin # => "think, feel and enjoy"
puts %w[ mitchell webb ].andjoin # => "mitchell and webb"
puts %w[ yes ].andjoin # => "yes"

puts %w[ happy fun monkeypatch ].andjoin(', ', ', and ') # => "happy, fun, and monkeypatch"
0

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


All Articles