Ruby, you can iterate over a string in various ways depending on whether you want to iterate by characters, bytes, or specific delimiters (like words or lines). Here are the common methods for iterating over strings:
1. Iterating by Characters:
You can iterate over each character in the string using the each_char
method
str = "hello"
str.each_char do |char|
puts char
end
Output
h
e
l
l
o
Alternatively, you can use chars
, which returns an array of the characters, and then iterate using each
str.chars.each do |char|
puts char
end
2. Iterating by Bytes:
If you need to iterate over the byte values of the string (especially useful in encoding situations), you can use the each_byte
method.
ruby
Copy code
str = "hello"
str.each_byte do |byte|
puts byte
end
Output:
Copy code
104
101
108
108
111
(These numbers represent the ASCII values of the characters.)
3. Iterating by Words:
You can split a string into words (usually by spaces) using split
, and then iterate over the array of words.
ruby
Copy code
str = "hello world"
str.split.each do |word|
puts word
end
Output:
Copy code
hello
world
4. Iterating by Lines:
If you have a multiline string, you can iterate over each line using the each_line
method.
ruby
Copy code
str = "hello\nworld"
str.each_line do |line|
puts line
end
Output:
Copy code
hello
world
You can also customize the line separator:
ruby
Copy code
str.each_line(",") do |line|
puts line
end
5. Using each_with_index
:
You can combine the iteration methods with each_with_index
to keep track of the index while iterating. This works for characters, words, lines, etc.
Iterating by characters with index:
ruby
Copy code
str = "hello"
str.each_char.with_index do |char, idx|
puts "#{idx}: #{char}"
end
Output:
makefile
Copy code
0: h
1: e
2: l
3: l
4: o
6. Iterating over Regex Matches:
You can use the scan
method to iterate over portions of a string that match a pattern (using a regular expression).
ruby
str = "hello 123 world 456"
str.scan(/\d+/) do |match|
puts match
end
Output:
Copy code
123
456
Summary of Methods:
each_char
: Iterates over each character.each_byte
: Iterates over each byte of the string.each_line
: Iterates over each line.split
+each
: Iterates over words by splitting the string.scan
: Iterates over regex matches.each_with_index
: Allows tracking the index during iteration.
These methods provide a lot of flexibility when you need to process strings in Ruby!