a = [“A”,“A”,“A”,“A”,“A”, “A”,“A”,“A”,“A”,“A”]
a[3…7] = “B”
QUESTION:
after code executes a = [“A”, “A”, “A”, “B”, “A”, “A”, “A”]
what should I do to make a = [“A”, “A”, “A”, “B”, “B”, “B”, “B”, “A”,
“A”, “A”]
a = [“A”,“A”,“A”,“A”,“A”, “A”,“A”,“A”,“A”,“A”]
a[3…7] = “B”
QUESTION:
after code executes a = [“A”, “A”, “A”, “B”, “A”, “A”, “A”]
what should I do to make a = [“A”, “A”, “A”, “B”, “B”, “B”, “B”, “A”,
“A”, “A”]
I understand that 
But I need some universal way to change values of arrays with 10+
elements
Found way:
b = []
a[3…7].size.times do b.push(“B”) end
a[3…7] = b
is there anything simplier?
Jeremy,
Thank you!
It’s very nice :))
On 3/18/2011 10:22, Ruby F. wrote:
Found way:
b = []
a[3…7].size.times do b.push(“B”) end
a[3…7] = bis there anything simplier?
Not necessarily any simpler, but perhaps a bit more efficient:
3…7.each { |i| a[i] = “B” }
Wrap it up into a nice method:
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”]
-Jeremy
You can use the fill method in the Array class
e.g from the Ruby docs
a.fill(“z”, 2, 2) #=> [“x”, “x”, “z”, “z”]
a.fill(“y”, 0…1) #=> [“y”, “y”, “z”, “z”]
Please refer to the Ruby docs for other ways to use the fill method
http://railsapi.com/doc/ruby-v1.9.2/classes/Array.html#M000097
On Fri, Mar 18, 2011 at 11:31 PM, Jeremy B. [email protected] wrote:
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”]
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs