给定一个包含一些单词的数组,循环遍历数组以显示每个单词中的字符数。
friends = ["Dan", "Mindy", "Suhasini", "Ryan"]
答案 0 :(得分:2)
如果您希望返回显示长度的数组,则可以使用以下命令:
friends = ["Dan", "Mindy", "Suhasini", "Ryan"]
p friends.map { |friend| friend.length }
答案 1 :(得分:1)
您可以使用数组显示字符数,如下所示。
friends = ["Dan", "Mindy", "Suhasini", "Ryan"]
def count_char(friends)
count = 0
friends.each do |word|
count = word.length
puts "'#{word}' has #{count} character(s)"
end
end
count_char(friends)
=>
'Dan' has 3 character(s)
'Mindy' has 5 character(s)
'Suhasini' has 8 character(s)
'Ryan' has 4 character(s)