【问题标题】:Return an array with integers in stead of strings返回一个包含整数而不是字符串的数组
【发布时间】:2015-02-20 20:05:14
【问题描述】:

我写了以下代码

a = [2,4,6]

def add_value_and_index(anArray)
newArray = []
anArray.each_with_index do |element, index|
    total = element + index
    total
    newArray <<"#{total}"
    newArray
  end
  newArray
  #newArray.to_i does not work
end

add_value_and_index(a)

这应该返回一个数组,它是索引号和值的组合。该方法有效。然而,我在字符串 => ["3","5"...] 中得到输出,而我想要整数 => [1,2,3] 中的输出。

我尝试添加 newArray.to_i 但这不起作用。关于如何将这个数组转换为整数的任何想法?

【问题讨论】:

    标签: ruby ruby-on-rails-3


    【解决方案1】:

    正如@humza 指出的那样,错误是newArray &lt;&lt; total
    "#{total}" 是字符串插值,它基本上是评估字符串中的占位符。

    这只是一个单一的解决方案...如果您有兴趣...

    a.collect.each_with_index {|num, index| num + index}
    

    map和collect也没有区别...
    Difference between map and collect in Ruby?

    【讨论】:

      【解决方案2】:
      newArray <<"#{total}" # WRONG
      

      您将字符串推入数组,期望最终获得整数。将上面的行更改为:

      newArray << total
      

      仅供参考,您可以使用map 清理此处的内容。

      def your_method(array)
        array.map.with_index do |element, index|
          element + index
        end
      end
      

      【讨论】:

      • each_with_index.map { |element,index| ... } 不是map.with_index
      • @FilipBartuzi,注意Enumerator#with_index 的定义位置。该方法的一个优点是它采用了一个参数(默认为0),即初始索引。
      猜你喜欢
      • 2018-11-16
      • 2018-12-11
      • 2015-10-17
      • 2018-12-04
      • 2015-05-10
      • 2011-09-20
      • 1970-01-01
      • 2021-07-17
      相关资源
      最近更新 更多