w3resource

Ruby Basic Exercises: Create a new string taking every other character starting with the first of a given string

Ruby Basic: Exercise-40 with Solution

Write a Ruby program to create a new string taking every other character starting with the first of a given string.

Ruby Basic Exercises: Create a new string taking every other character starting with the first of a given string

Ruby Code:

def string_test(str)
    str1 = ""
    str.split("").each_with_index do |char, index|
        str1 += char unless index % 2 == 1     
    end
    return str1
end
print string_test('abcdefgij'),"\n"
print string_test('abcdefg'),"\n"
print string_test('abcdef'),"\n"
print string_test('abc'),"\n"
print string_test('ab'),"\n"

Output:

acegj
aceg
ace
ac
a

Flowchart:

Flowchart: Create a new string taking every other character starting with the first of a given string

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check a given string contains 'i' characters.
Next: Write a Ruby program to count the number of 5's in an given array.

What is the difficulty level of this exercise?