Ruby: is there a way that I can accomplish the assignment as follows: self.value_at_location (x, y) = value?

I know what I could do

self.value_at_location=(x,y,value) 

defining a method as value_at_location=(x,y,value)

but for readability, I think it would be AWESOME if value_at_location(x,y)=(value) were possible. or something like that.

Any suggestions?

+4
source share
3 answers

No, you cannot define the setter method for foo(x,y) = value .

But what you can do is define []=(x,y,value) so that you can call self[x,y] = value .

+4
source

It is possible, hypothetically, to do some strange things with metaprogramming:

 class Point ... def location_at_value(x, y) x = Object.new x.define_method(:=) { |value| @value[x, y] = value } return x end end 

Please note that I have not tested this, but it should work theoretically. This does not work, see comment below.

+1
source

Why would you want to do that? It would be much easier to do this:

 class Point attr_reader :x, :y, :value attr_accessor :value def initialize @value = [@x,@y] end def value_at xy @x = x @y = y end end 
0
source

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


All Articles