Insert at index

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.

On Sep 24, 2012, at 6:34 AM, Geena T. 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.

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

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

On Mon, Sep 24, 2012 at 2:28 PM, Geena T. [email protected] wrote:

aabc
aaabc
But the desired output is
abc
bac
bca

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

Geena T. 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”

Robert K. 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
=> 3

Kind regards

robert

coooool,…

it works, st.dup was what i was searching for

Thank you:-)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs