Search code examples
rubyblockproc

Ruby ! Methods or Procs


I'm wanting to modify a variable in place, replicating the methodname! syntax as opposed to reassigning a new modified value to the same var. Can I do this with a proc? I'm still learning procs and see them as quite useful is used properly.

a = "Santol bag 85.88   www.example.com/products/16785
Shaddock    kg  2.94    www.example.com/products/4109
Palm Fig    5kg 94.34   www.example.com/products/23072
Litchee lb  95.85   www.example.com/products/2557"

a = a.split("\n")

linebreak = Proc.new { |text| text.split("\n") }
linebreak![a]

that first reassignment seems cumbersome. The proc version I would like to see if I can perform it inline. Is this possible?


Solution

  • methodname! is just a convention - usually there are two flavours of the same method - one without bang and one with bang. If you want to have a proc that mutates its params, you need to implement it using mutating methods.

    And in this case it's not possible, because you're trying to transform a string into an array. You have to reassign the variable:

    linebreak = Proc.new { |text| text.split("\n") }
    a = linebreak.call(a)