in some cases, specifying the starting and the length may be also handy, eg,
a=["A"]*10
#=> ["A", "A", "A", "A", "A", "A", "A", "A", "A", "A"]
a[3,4]=["B"]*4
#=> ["B", "B", "B", "B"]
a
#=> ["A", "A", "A", "B", "B", "B", "B", "A", "A", "A"]
and ff jeremy's wrapping,
class Array
def replacex start,length, item
self[start,length]=[item]*length
end
end
#=> nil
a=["A"]*10
#=> ["A", "A", "A", "A", "A", "A", "A", "A", "A", "A"]
a.replacex 3, 4,"B"
#=> ["B", "B", "B", "B"]
a
#=> ["A", "A", "A", "B", "B", "B", "B", "A", "A", "A"]
best regards -botp
···
On Fri, Mar 18, 2011 at 11:31 PM, Jeremy Bopp <jeremy@bopp.net> wrote:
On 3/18/2011 10:22, Ruby Fan wrote:
Found way:
b =
a[3...7].size.times do b.push("B") end
a[3...7] = b
3...7.each { |i| a[i] = "B" }
class Array
def replace_range_with(range, replacement)
range.each { |i| self[i] = replacement }
self
end
end
a = ["A", "A", "A", "A", "A"]
a.replace_range_with(2...4, "B") #=> ["A", "A", "B", "B", "A"]