D
Doug Beaver
hello,
i'm looking for a nice idiomatic way to append to an array. i'm porting
some encryption code from C to ruby, i don't have the code in front of
me but a relevant example is below:
def translate(str="")
ret = []
str.each_byte { |byte| ret << byte }
ret
end
bytes = []
bytes << translate("foo")
bytes += translate("foo")
p bytes
i'm using ruby 1.6.8, btw...
elsewhere in my code, i'm using << to append bytes onto the bytes array,
but for the functions that return arrays of bytes, i have to use += to
make sure the flattened values get added to the target array. if i use
<<, it appends the array returned from the function back onto the target
array. i'd like to use << everywhere as it makes the code more readable
(imo), so is there some syntax i can throw in front of the translate()
call to make the << do the right thing?
i've considered both overloading Array.<< or making my own subclass and
making a smarter <<. i realize that << can't tell if your intent is to
append the array itself ([1,2,3]) or its values (1,2,3). i guess my
real question is, can i get the desired behavior without making a
subclass or redefining <<? i hope my question is clear...
thanks,
doug
i'm looking for a nice idiomatic way to append to an array. i'm porting
some encryption code from C to ruby, i don't have the code in front of
me but a relevant example is below:
def translate(str="")
ret = []
str.each_byte { |byte| ret << byte }
ret
end
bytes = []
bytes << translate("foo")
bytes += translate("foo")
p bytes
i'm using ruby 1.6.8, btw...
elsewhere in my code, i'm using << to append bytes onto the bytes array,
but for the functions that return arrays of bytes, i have to use += to
make sure the flattened values get added to the target array. if i use
<<, it appends the array returned from the function back onto the target
array. i'd like to use << everywhere as it makes the code more readable
(imo), so is there some syntax i can throw in front of the translate()
call to make the << do the right thing?
i've considered both overloading Array.<< or making my own subclass and
making a smarter <<. i realize that << can't tell if your intent is to
append the array itself ([1,2,3]) or its values (1,2,3). i guess my
real question is, can i get the desired behavior without making a
subclass or redefining <<? i hope my question is clear...
thanks,
doug