ruby - 如何将数组的所有其他元素相乘?

标签 ruby

假设我有一个这样的数组:

[1,2,3,4,5,6,7]

我怎样才能将该数组除第一个以外的所有其他数字乘以 2 所以我的新数组看起来像这样

[1,4,3,8,5,12,7]

最佳答案

您可以使用 mapwith_index:

[1,2,3,4,5,6,7].map.with_index{|v,i| i % 2 == 0 ? v : v * 2 } 
# => [1, 4, 3, 8, 5, 12, 7]

关于ruby - 如何将数组的所有其他元素相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19027717/

相关文章:

ruby - 从 Ruby 中的 MongoDB 嵌套哈希中提取正确的字符串

html - 纯 css 无法正确加载到 Ruby on Rails 中

ruby - 在返回散列或 nil 的方法上使用 ruby​​ 'or equals' ||=

ruby-on-rails - Ruby on Rails 风格指南,方法参数周围的括号

ruby - 使用 Homebrew 安装 opam 时出现 "require: cannot load such file -- mach"

ruby-on-rails - 打开终端时自动运行命令(Linux Mint 16)

ruby - 为什么这不起作用,ruby 中字符串的未定义空白

ruby - 来自 Mechanize 的 NoMethodError

ruby - Nokogiri 'not' 选择器

ruby-on-rails - 使用 Devise 实现双因素身份验证