在给定索引数组的情况下输出数组的值

问题描述 投票:0回答:3

给定一个像words = ["hello", ", ", "world", "!"]这样的数组,我需要操作由字母组成的元素,所以我最后会得到一个字符串,如"*hello*, *world*!"

我已设法从数组中检索包含使用words.map.with_index { |element, index| index if element[[/a-zA-Z+/]] == element }.compact的字母的索引,这些字母是[0, 2]

我如何在函数中使用这些索引,以便我可以操作这些单词?

arrays ruby string loops
3个回答
2
投票

你不需要索引。如果您希望能够对每个数组元素应用任意逻辑,请使用不带索引的map

words.map{|w| w.gsub(/[a-zA-Z]+/,'*\0*')}.join

正如其他人所指出的那样,对于你给出的例子,你根本不需要处理数组,只需先将它连接成一个字符串。例如:

words.join.gsub(/[a-zA-Z]+/,'*\0*')

0
投票

尝试使用正则表达式,这将使您的工作轻松。您可以在数组中获取元素后对其进行操作

words = ["hello", ", ", "world", "!"]
array = []
words.each do |a|
  array << a if /\w/.match(a)
end

puts array

hello
world

0
投票
words.reject { |word| word.match?(/\p{^L}/) }.
      map { |word| "*%s*" % word }.
      join(', ')
  #=> "*hello*, *world*"
© www.soinside.com 2019 - 2024. All rights reserved.