"<" method for array

E

Eva

SGksDQoNCkkgaGF0ZSB0aGVyZSBpcyBub3QgYSAiPCIgbWV0aG9kIGZvciBhcnJheSBvYmplY3Qu
DQpTaW5jZSB0aGVyZSBpcyB0aGUgIjw8IiBmb3IgYWRkaW5nIGFuIGVsZW1lbnQsIHdoeSBub3Qg
aGF2ZSB0aGUgIjwiIGZvciB0cnVuY2F0aW5nIHRoZW4gZmlsbGluZyB1cCB0aGUgYXJyYXk/DQoN
Ckkga25vdyBJIGNhbiB3cml0ZSBvbmU6DQoNCmlyYihtYWluKTowMDk6MD4gY2xhc3MgQXJyYXkN
CmlyYihtYWluKTowMTA6MT4gICBkZWYgPChhKQ0KaXJiKG1haW4pOjAxMToyPiAgICAgIGNsZWFy
DQppcmIobWFpbik6MDEyOjI+ICAgICAgc2VsZiA8PCBhDQppcmIobWFpbik6MDEzOjI+ICAgZW5k
DQppcmIobWFpbik6MDE0OjE+IGVuZA0KDQoNCkJ1dCBpdCdzIG5vdCB0aGF0IGNvbnZlbmllbnQg
d2hlbiBJIHdhbnQgaXQuDQoNClRoYW5rcyE=
 
Y

Yossef Mendelssohn

Hi,

I hate there is not a "<" method for array object.
Since there is the "<<" for adding an element, why not have the "<" for t=
runcating then filling up the array?
I know I can write one:

irb(main):009:0> class Array
irb(main):010:1> =A0 def <(a)
irb(main):011:2> =A0 =A0 =A0clear
irb(main):012:2> =A0 =A0 =A0self << a
irb(main):013:2> =A0 end
irb(main):014:1> end

But it's not that convenient when I want it.

That would surprise the hell out of me.

Established convention is that << is the "left shift" or "append"
operator, which will change the receiver. On the other hand, < is the
"less than" operator, which simply compares the receiver to the
argument, no change whatsoever.

You *can* redefine < to do whatever you want, but I'm not sure why you
would define it this way.
 
B

Brian Candler

Eva wrote in post #964024:
I hate there is not a "<" method for array object.

If there were, I would expect it to work like this:
class Array
include Comparable
end
[1] < [2] => true
[1] < [1] => false
[1] < [1,0]
=> true
Since there is the "<<" for adding an element, why not have the "<" for
truncating then filling up the array?

Array#replace already does that, except you have to give it the element
also wrapped in an Array.
a = [1,2,3] => [1, 2, 3]
a.object_id => 69928599426960
a.replace [4] => [4]
a => [4]
a.object_id
=> 69928599426960
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,141
Messages
2,570,818
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top