0

This line of code:

@instance.attributes.each{|key, value| @instance.send(key) = nil}

yields this error:

syntax error, unexpected '=', expecting '}'

I'm having trouble understanding why that is.. When I write something like:

@instance.attributes.each{|key, value| puts @instance.send(key)}

it behaves as expected, outputting the value of each attribute. Why does it work as a getter but not as a setter in this context? Is there a problem with my syntax?

Thanks a lot.

2
  • 1
    BTW, if @instance is an ActiveRecord instance, you could use @instance[key] = nil, see ActiveRecord::AttributeMethods#[]= Commented Apr 2, 2019 at 16:03
  • I could have sworn that that was the first thing I tried, but right you are. Thanks a lot. Commented Apr 2, 2019 at 16:34

1 Answer 1

3
@instance.send(key)

Is calling the getter method. To call the setter method, try:

@instance.attributes.each{|key, value| @instance.send("#{key}=", nil)}
Sign up to request clarification or add additional context in comments.

4 Comments

This worked. Thanks a lot. Why is it that I can ordinarily call a setter method without using this syntax? eg @instance.attribute = nil rather than @instance.attribute=(nil)
That's a good question. I don't know the precise answer and hesitate to speculate. I suppose some digging through the source code would likely reveal the answer. Or, one of the gurus may swing by and tell us why. Apologies!
@JoshKestenberg it's called syntactic sugar. The parser detects certain structures and converts them, so you can write @instance.attribute = nil to invoke a setter, or 1 + 2 instead of 1.+(2).
@Stefan - Great explanation. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.