Hi,
Is there any alternative for insert in string. I need to insert
different
characters at different indices using a loop, but since insert modifies
the string it goes wrong.
Please help.
···
--
Posted via http://www.ruby-forum.com/.
Hi,
Is there any alternative for insert in string. I need to insert
different
characters at different indices using a loop, but since insert modifies
the string it goes wrong.
Please help.
--
Posted via http://www.ruby-forum.com/.
I'm not sure I understand the full question, but since you are looping, one way to do this:
new_variable = old_string.split(/(your value here)/)
new_variable is an array so then you can do this:
new_variable.each_with_index do | value, index |
# Your code here to make the change
# then just substitute the new change like this:
new_variable(index) = (your new code/variable)
end
# Then just put your array back into a string using .join.
Wayne
On Sep 24, 2012, at 6:34 AM, Geena Tho wrote:
Hi,
Is there any alternative for insert in string. I need to insert
different
characters at different indices using a loop, but since insert modifies
the string it goes wrong.
Please help.
Thank you Wayne, But
(0..n-1).each do |i|
st.insert(i,ch)
end
This is my code, st is my string. I need to insert a character, say ch.
n is 3
for example, if st = 'ab' and ch = 'c' i get:
abc
aabc
aaabc
But the desired output is
abc
bac
bca
--
Posted via http://www.ruby-forum.com/.
Geena Tho wrote in post #1077284:
Hi,
Is there any alternative for insert in string. I need to insert
different
characters at different indices using a loop, but since insert modifies
the string it goes wrong.
Please help.
str="foobar"
=> "foobar"
str[0...3]+"x"+str[3..-1]
=> "fooxbar"
str
=> "foobar"
--
Posted via http://www.ruby-forum.com/\.
The last two outputs have order of "a" and "b" reversed - that can
never be the result of simply inserting something into "ab". Are
those typos or is it intentional? If it is intentional, what is it
that you _really_ want?
In case of type, please have a look:
irb(main):001:0> st = 'ab'
=> "ab"
irb(main):002:0> ch = 'c'
=> "c"
irb(main):003:0> 3.times {|i| puts st.dup.insert(i, ch)}
cab
acb
abc
=> 3
Kind regards
robert
On Mon, Sep 24, 2012 at 2:28 PM, Geena Tho <lists@ruby-forum.com> wrote:
Thank you Wayne, But
(0..n-1).each do |i|
st.insert(i,ch)
end
This is my code, st is my string. I need to insert a character, say ch.
n is 3for example, if st = 'ab' and ch = 'c' i get:
abc
aabc
aaabc
But the desired output is
abc
bac
bca
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
Robert Klemme wrote in post #1077298:
In case of type, please have a look:
irb(main):001:0> st = 'ab'
=> "ab"
irb(main):002:0> ch = 'c'
=> "c"
irb(main):003:0> 3.times {|i| puts st.dup.insert(i, ch)}
cab
acb
abc
=> 3Kind regards
robert
coooool,..
it works, st.dup was what i was searching for
Thank you:-)
--
Posted via http://www.ruby-forum.com/\.