Array range values assignment

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"]

···

--
Posted via http://www.ruby-forum.com/.

Just
a[3...7] = ['B','B','B','B'].

Works at least in 1.9.2.

···

2011/3/18 Ruby Fan <sweensonti@garrifulio.mailexpire.com>

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"]

--
Posted via http://www.ruby-forum.com/\.

I understand that :slight_smile:

But I need some universal way to change values of arrays with 10+
elements

···

--
Posted via http://www.ruby-forum.com/.

Found way:

b = []
a[3...7].size.times do b.push("B") end
a[3...7] = b

is there anything simplier?

···

--
Posted via http://www.ruby-forum.com/.

Jeremy,

Thank you! :slight_smile: It's very nice :))

···

--
Posted via http://www.ruby-forum.com/.

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

···

--
Posted via http://www.ruby-forum.com/.

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

···

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

is there anything simplier?

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"]