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 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:
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?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/ruby-exercises/basic/ruby-basic-exercise-40.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics