[YANQ] - how to create/modify []=

Hi Ruby friends,

I would like to modify or create own Array#[]= method to return the array.

Currently,

C:\family\ruby>irb
irb(main):001:0> a = [1,2,3,4]
[1, 2, 3, 4]
irb(main):002:0> a[1] = 6
6 <====== returns value inserted
irb(main):003:0> a
[1, 6, 3, 4]

I would like a[1] = 6 to return array a itself, so I can do eg,

a = [1,2,3,4]
p (a[1]=6).sort

I’m reading sir Dave’s online axe book so a chapter reference would be fine.
You could also tell me how you search it (since I’ve search but cannot find
it, maybe my query is not good enough).

Many thanks,
-botp

Hi Ruby friends,

I would like to modify or create own Array#= method to return the array.

[…]

Many thanks,
-botp

Now this is strange: someone who doesn’t like modifying objects wants to modify
classes instead!

Anyway, I thought it would be really easy, but I can’t seem to do it.

Cheers,
Gavin

···

From: “Peña, Botp” botp@delmonte-phil.com

I would like to modify or create own Array#= method to return the array.

Be carefull with this, because you'll perhaps use some module which don't
expect to have this result. Or someone will use a method written by you
and will be surprised by this result. This can give bugs very diificult to
find.

You could also tell me how you search it

See #alias, something like

   class Array
      alias __acc = unless method_defined? :__acc
      def =(a, b)
         __acc(a, b)
         self
      end
   end

Guy Decoux

“Peña, Botp” botp@delmonte-phil.com writes:

I would like a[1] = 6 to return array a itself, so I can do eg,

a = [1,2,3,4]
p (a[1]=6).sort

I’m reading sir Dave’s online axe book so a chapter reference would be fine.
You could also tell me how you search it (since I’ve search but cannot find
it, maybe my query is not good enough).

module MyArray
def =(x, y)
super x, y
self
end
end

a = [1,2,3,4]
a.extend MyArray
p((a[1]=6).sort) #=> [1, 3, 4, 6]

···


eban

I would like to modify or create own Array#= method to return the array.

[…]

Many thanks,
-botp

Now this is strange: someone who doesn’t like modifying objects wants to modify
classes instead!

Anyway, I thought it would be really easy, but I can’t seem to do it.

Cheers,
Gavin

I’d probably do something in the vincinity of,
class SArray < Array
def = (a, b)
super(a, b)
self
end
end

or perhaps:
class Array
def set_element(a, b)
self[a] = b
self
end
end

altering the basic = behavior seems IMO like a pretty bad idea.

Having a hash argument would be prettier - then you can say
a.set({1=>6, 2=>5, 3=>-1}).sort

martin

···

Bj bjst01@student.bth.se wrote:

class Array
def set_element(a, b)
self[a] = b
self
end
end

altering the basic = behavior seems IMO like a pretty bad idea.