ruby-on-rails - 如何遍历匹配正则表达式的数组元素?

标签 ruby-on-rails ruby

是否有一种方法可以与“each”一起使用,根据正则表达式匹配来过滤数组元素?

例如,我有以下数组:

arr = ["one", "has_two", "has_tree", "four"]

我想循环进入这个数组并只获取以“has”开头的元素。

下面的代码对所有元素进行循环

arr.each |element| do

....

end

最佳答案

您可以使用 Enumerable's grep method这样做:

arr.grep(/^has/).each do |element|
  ...
end

关于ruby-on-rails - 如何遍历匹配正则表达式的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6947312/

相关文章:

ruby-on-rails - rails 流

ruby - 我可以模拟 RSpec double 的类名吗?

ruby-on-rails - 每当 gem : I set :output but the logfile doesn't show up where I'd expect it to

带有嵌入式 Ruby : How to safely assign a ruby value to a javascript variable 的 Javascript

ruby-on-rails - Rails 3.2.2 和 Rocket_tag 没有这样的列

ruby-on-rails - Rails,在像/books/:slug, :to => 'books#show' , slug :/. *?/什么是slug :/. *?/doing?

ruby-on-rails - 如何在已被 Rails 转义的正则表达式中转义\\?

ruby-on-rails - 事件记录 : milliseconds aren't taken into account when using a where clause

ruby - 导轨 : Is there a way of having only one contact form for a site that generates different HTML emails depending on what page it came from?

ruby - 在 Ruby 中获取 UTC 偏移量