arrays - 另一个数组中字符串长度的数组

标签 arrays ruby string string-length

我需要一个数组,列出不同数组中每个元素的字母数:

words = ["first", "second", "third", "fourth"]

我尝试为每个元素的长度创建一个变量。这:

first = words[0].length
second = words[1].length
third = words[2].length
fourth = words[3].length
letters = [first, second, third, fourth]
puts "#{words}"
puts "#{letters}"
puts "first has #{first} characters."
puts "second has #{second} characters."
puts "third has #{third} characters."
puts "fourth has #{fourth} characters."

输出:

["first", "second", "third", "fourth"]
[5, 6, 5, 6]
first has 5 characters.
second has 6 characters.
third has 5 characters.
fourth has 6 characters.

但这似乎是一种低效的做事方式。有没有更可靠的方法来做到这一点?

最佳答案

跳过字长数组并使用 Array#each :

words.each { |word| puts "#{word} has #{word.size} letters" }
#first has 5 letters
#second has 6 letters
#third has 5 letters
#fourth has 6 letters

如果由于某种原因您仍然需要字大小数组,请使用 Array#map :

words.map(&:size) #=> [5, 6, 5, 6]

关于arrays - 另一个数组中字符串长度的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48969796/

相关文章:

css - Ruby on Rails--提交按钮和页面与网页一样宽

Java括号替换为空字符串

json - 有没有更快的方法来解析 Java 中有效整数的字符串?

java - 如何用不同的子字符串替换多个子字符串?

PHP 数组引用;将引用保存在数组中供以后使用

Jquery 为什么我无法显示对象?

javascript - 将数组拆分为无序列表?

javascript - 如何在 Javascript 中将数组切换到对象中的数组?

Centos6上的Ruby安装问题

ruby-on-rails - 将 Ruby on Rails HTML 表导出到 .xls 文件