Abi Travers
Abi Travers

Reputation: 21

How to convert an input string into an array which contains each character of that string - ruby

Hi I have to convert a string which is input in an unrelated method, into an array where each of it's characters is an element. I then need to iterate through this array printing each odd character. I am mainly having issues putting this string into an array, I am writing in Ruby. Any help would be amazing please. Thanks you.

Upvotes: 1

Views: 346

Answers (4)

hoffm
hoffm

Reputation: 2436

This should do the trick:

def print_odd_chars(str)
  str.each_char.each_with_index do |char, i|
    print char if i.odd?
  end
end

Upvotes: 0

Lasse Sviland
Lasse Sviland

Reputation: 1517

To print each odd character you can split the string on every character then test if the index is odd like this:

def unrelated_method(input_string)
  input_string.split('').each_with_index do |char, index|
    puts char if index.odd?
  end
end

Another option is to loop through each character and keep track fo the index yourself, like this:

def unrelated_method(input_string)
  index = 0
  input_string.each_char do |char|
    puts char if index.odd?
    index += 1
  end
end

And you could, of course, short it down to this:

def unrelated_method(input_string)
  input_string.split('').each_with_index { |ca, i| puts ca if i.odd? }
end

Upvotes: 1

Michał Młoźniak
Michał Młoźniak

Reputation: 5556

You can use #each_char method which will give an enumerator so you can iterate over chars.

value = "Hello, World"
value.each_char { |char| puts char }

Upvotes: -1

Gerry
Gerry

Reputation: 10507

You can use chars to get an array of all characters of a given string, for example:

input = "string"

input.chars
#=> ["s", "t", "r", "i", "n", "g"]

Upvotes: 2

Related Questions