2

I often do the following:

@value = @value.some_method

But isn't there a shorter syntax for that in ruby? Some methods offer bang equivalents, but sadly not all...

For iterations one can use:

 i += 1

Is that, or something similar, also available for my code snippet above?

4

2 回答 2

2

There's nothing that does this in a shorter way.

To be fair, it is an unusual pattern, and while not especially rare, would lead to confusion if there was an operator like:

@value .= some_method

How is that even supposed to be parsed when reading?

As the Tin Man points out, in-place operators are really what are best here.

于 2013-01-03T14:55:34.663 回答
1

You cannot do that taking the actual variable as the receiver because there is no way to get to the name of the variable. Instead, you need to use the name of the variable like this:

class A
  attr_accessor :value
  def change_to_do_something name
    instance_variable_set(name, "do something")
  end
end

a = A.new

a.value = "Hello"
p a.value
# => "Hello"

a.change_to_do_something(:@value)
p a.value
# => "do something"
于 2013-01-03T14:58:46.120 回答