Hi there!
I’m a ruby newbie, and I’m searching for a way to iterate every char in
a string, but I cannot find any easy way. My problem is to look at every
char in a string and match it with some known letter.
I use the String#each_byte iterator for now, but it still be a poor
solution
Thanks,
Hi there!
I’m a ruby newbie, and I’m searching for a way to iterate every
char in a string, but I cannot find any easy way. My problem is to
look at every char in a string and match it with some known letter.
I use the String#each_byte iterator for now, but it still be a poor
solution
Thanks,
shinya.
The usual idiom is str.split(//).each do |character|
# do stuff with character
end
eg:
logan:/Users/logan% irb
irb(main):001:0> str = “Hello, world!”
=> “Hello, world!”
irb(main):002:0> str.split(//).each do |character|
irb(main):003:1* puts character
irb(main):004:1> end
H
e
l
l
o
,
w
o
r
l
d
!
=> [“H”, “e”, “l”, “l”, “o”, “,”, " ", “w”, “o”, “r”, “l”, “d”, “!”]
if the extraneous typing bothers you, you can always add it to String.
class String
def each_char(&block)
split(//).each(&block)
self
end
end
“Wrong” is a strong word, but I’d say this isn’t ideal Ruby for two
reasons:
Generally in Ruby internal iterators (i.e. each, each_byte, etc.)
are preferred over external iterators like what you have here (and for
and while loops.)
Your code isn’t as efficient, though it wasn’t as bad as I thought:
Hi there!
I’m a ruby newbie, and I’m searching for a way to iterate every char in
a string, but I cannot find any easy way. My problem is to look at every
char in a string and match it with some known letter.
If you just want to know if a string contains a character:
puts "Yep!" if str.include?("X")
I use the String#each_byte iterator for now, but it still be a poor
solution
Others have suggested various iterators, but why not use standard jcode
lib?
Others have suggested various iterators, but why not use standard jcode lib?
require 'jcode'
str.each_char { |c| puts c }
In case anyone is curious, the above just uses scan(/./m), and is even
slower in my benchmark because of the extra method calls. But in
reality all are quite fast enough, and the performance differences
aren’t all that significant.
Strange it is not a part of Ruby as the char is the most natural
part of
a string.
I don’t think that is true. The semantics of each_byte are quite clear
but exactly what is a character? In some encodings
one byte is the same as one character but in other encodings it might
be two bytes or in others in might be a variable number of bytes.
Iterating by ‘character’ only has meaning with respect to a character
set
encoding and a Ruby string generally doesn’t have that sort of
information.
I think it is has been said before but, a Ruby string is more like an
array of bytes than a sequence of code points in an (implicit)
character set.