For example, if you want to output only the odd-numbered characters in the alphabet.
str = "abcdefghijklmnopqrstuvwxyz"
str.each_char.with_index{|c, index|
print c if index % 2 == 0
}
# => acegikmoqsuwy
I will explain each of them. I would be grateful if you could point out any mistakes you made.
each_char By using the chars method (also known as each_char) of the String class, you can process the characters in the string while extracting them one by one.
x = "TOKYO"
y = x.chars
# => ["T", "O", "K", "Y", "O"]
each.with_index It is used when you want to number each data while turning each. In this case, each character extracted first is stored in the variable c. Then, if the variable index numbered by each.with_index is divisible by 2, the variable c is output. If it is divisible by 2, it will be an even number, but since the programming number includes 0, it has been reversed.
str = "abcdefghijklmnopqrstuvwxyz"
str.each_char.with_index{|c, index|
print c if index % 2 == 0
}
# => acegikmoqsuwy
instance method String#each_char https://docs.ruby-lang.org/ja/latest/method/String/i/each_char.html A program that capitalizes and outputs only odd numbers http://sinyt.hateblo.jp/entry/2013/12/22/183217 How to use each_with_index https://qiita.com/tsuchinoko_run/items/5cef7dd9d8baf48ffde7
Recommended Posts