Array range values assignment

R

Ruby Fan

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

Gunther Diemant

[Note: parts of this message were removed to make it a legal post.]

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

Works at least in 1.9.2.
 
R

Ruby Fan

I understand that :)

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

Ruby Fan

Found way:

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

is there anything simplier?
 
J

Jeremy Bopp

Found way:

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

is there anything simplier?

Not necessarily any simpler, but perhaps a bit more efficient:

3...7.each { |i| a = "B" }

Wrap it up into a nice method:

class Array
def replace_range_with(range, replacement)
range.each { |i| self = replacement }
self
end
end

a = ["A", "A", "A", "A", "A"]
a.replace_range_with(2...4, "B") #=> ["A", "A", "B", "B", "A"]


-Jeremy
 
B

botp

Found way:

b =3D []
a[3...7].size.times do b.push("B") end
a[3...7] =3D b
3...7.each { |i| a =3D "B" }

class Array
=A0def replace_range_with(range, replacement)
=A0 =A0range.each { |i| self =3D replacement }
=A0 =A0self
=A0end
end
a =3D ["A", "A", "A", "A", "A"]
a.replace_range_with(2...4, "B") #=3D> ["A", "A", "B", "B", "A"]


in some cases, specifying the starting and the length may be also handy, e=
g,

a=3D["A"]*10
#=3D> ["A", "A", "A", "A", "A", "A", "A", "A", "A", "A"]

a[3,4]=3D["B"]*4
#=3D> ["B", "B", "B", "B"]

a
#=3D> ["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]=3D[item]*length
end
end
#=3D> nil

a=3D["A"]*10
#=3D> ["A", "A", "A", "A", "A", "A", "A", "A", "A", "A"]

a.replacex 3, 4,"B"
#=3D> ["B", "B", "B", "B"]

a
#=3D> ["A", "A", "A", "B", "B", "B", "B", "A", "A", "A"]


best regards -botp
 

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
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top