Robert Klemme
10/9/2007 9:19:00 PM
On 09.10.2007 19:41, Matt Margolis wrote:
> Robert Klemme wrote:
>> On 09.10.2007 18:12, Logan Capaldo wrote:
>>> On 10/9/07, Matt Margolis <matt@mattmargolis.net> wrote:
>>>> Logan Capaldo wrote:
>>>>> On 10/9/07, Matt Margolis <matt@mattmargolis.net> wrote:
>>>>>> Is achieving this behavior as simple as redefining some operator
>>>>>> methods
>>>>>> like == or is this sort of behavior not possible in Ruby?
>>>>>>
>>>>>>
>>>>> The latter.
>>>>>
>>>
>>> Quoting myself. In other words, no you can't do it.
>>
>> An alternative approach might be to use 'case' expressions instead of
>> 'if' and implement #=== properly in that class.
>>
>> Matt, what are you implementing? Why is this functionality crucial?
>>
>> Kind regards
>>
>> robert
>>
> I can't really get into specifics but basically I am doing something
> like the following
>
> module PrimitiveExtensions
> attr_accessor :name
> def to_extended_primitive(name)
> @name = name
> return self
> end
>
>
> I then mix this in to String, Fixnum, Float etc...
>
> MyClass contains
> def my_val=(obj)
> obj.to_extended_primitive("MyVal")
> end
> def other_val=(obj)
> obj.to_extended_primitive("OtherVal")
> end
This seems a strange way to use assignment since you do not modify the
receiver but the sender. I'd say this will likely lead to hard to code
that is hard to understand.
> The purpose of all of this is to unify an interface so that I can store
> primitive values along with a name without having to go through a
> container class to get at the value.
> a = MyClass.new.my_val = 7
> and then later be able to go back and do something like
> a.name and get back "MyVal"
>
> This approach works for all the base types except for true and false
> since they are Singletons so I can't store a @name on them.
I doubt this approach works for all basic types since you will get
aliasing effects with Fixnums, i.e. you set the name in one place and it
will be visible on all other places as well as Fixnums are singletons
per value.
I do not know why you are so eager to have the attribute stored in the
primitive value. Considering what I have seen of your requirements I
would probably do something like this
NamedValue = Struct.new :value, :name
Kind regards
robert