Rich_F
Rich_F

Reputation: 2046

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?

Upvotes: 2

Views: 94

Answers (2)

mrzasa
mrzasa

Reputation: 23307

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)

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

This is surely possible, you just need to modify the string inplace

linebreak = ->(text) { text.replace text.split("\n").join(",") }
a = "foo\nbar"
linebreak[a]
#⇒ "foo,bar"
a
#⇒ "foo,bar"

What is not possible, is to change the class in place, that’s why split won’t work (called on a string, it returns an array.)

Upvotes: 7

Related Questions