Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,401 questions

56,365 answers

573 users

How to convert a string to an array of characters in Ruby

1 Answer

0 votes
#
# Convert a String into an Array of individual characters.
#
# In Ruby, String already behaves as a sequence of characters.
# However, some APIs or algorithms may require an explicit Array
# containing each character as a separate element.
#

# Converts a string to an array of characters.
#
# @param text [String] The source string.
# @return [Array<String>] An array containing one character per element.
#
# Implementation notes:
# - String#chars is the idiomatic Ruby way to split a string into
#   individual characters.
# - Ruby handles Unicode correctly, so multi-byte characters are
#   returned as expected.
#
def string_to_char_array(text)
  raise ArgumentError, 'text must be a String' unless text.is_a?(String)

  text.chars
end

#
# Program entry point.
#
def main
  text = 'Hello, World!'

  characters = string_to_char_array(text)

  puts "Original string: #{text}"
  puts
  puts 'Character array contents:'

  characters.each_with_index do |character, index|
    puts "characters[#{index}] = '#{character}'"
  end
end

main


# run:
#
# Original string: Hello, World!
# 
# Character array contents:
# characters[0] = 'H'
# characters[1] = 'e'
# characters[2] = 'l'
# characters[3] = 'l'
# characters[4] = 'o'
# characters[5] = ','
# characters[6] = ' '
# characters[7] = 'W'
# characters[8] = 'o'
# characters[9] = 'r'
# characters[10] = 'l'
# characters[11] = 'd'
# characters[12] = '!'
# 

 



answered 2 days ago by avibootz
...