-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringsIteration.rb
More file actions
66 lines (46 loc) · 1.95 KB
/
stringsIteration.rb
File metadata and controls
66 lines (46 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Cause the version, strings manipulation can be done by two ways:
# In Ruby 1.8, there's a single each method (remember Enumerable?) which allowed it to iterate over lines of data. While it might seem like a logical option to have, how would one go about iterating on each byte or each character? It turns out that it was not so clean, and people had to resort to tricks for some of these functionalities.
# With Ruby 1.9, each was removed from the String class and is no longer an Enumerable. Instead, we have more explicit choices based on what we need to iterate - bytes, chars, lines or codepoints.
# - each_byte iterates sequentially through the individual bytes that comprise a string;
# - each_char iterates the characters and is more efficient than [] operator or character indexing;
# - each_codepoint iterates over the ordinal values of characters in the string;
# - each_line iterates the lines.
# For example:
money = "¥1000"
money.each_byte {|x| p x} # first char represented by two bytes
# 194
# 165
# 49
# 48
# 48
# 48
money.each_char {|x| p x} # prints each character
# "¥"
# "1"
# "0"
# "0"
# "0"
# Without a doubt, Ruby 1.9 makes iteration easier to understand and implement. Hence, we'll stick with Ruby 1.9 and later versions for current and other challenges (unless otherwise stated).
# Challenge: Write the method count_multibyte_char which takes a string as input and returns the number of multibyte characters (byte size > 1) in it.
# For example:
count_multibyte_char('¥1000')
# 1
# Solution:
def count_multibyte_char (var)
count = 0
var.each_char {|c| count += 1 if c.bytesize > 1}
count
end
# Solution evolution:
def count_multibyte_char_evo (str)
str.each_char.count{|x| x.bytesize > 1}
end
# Solution 1:
# \p{ASCII} All ASCII:[\x00-\x7F]
def count_multibyte_char1 str
str.count "^\x00-\x7F" # ^ means not match the regex ALL ASCII
end
# Solution 2:
def count_multibyte_char2 str
str.each_char.select { |c| c.bytesize > 1 }.count
end