arrays - 如何对整数字符串数组求和?
问题描述
问题:将数组字符串元素转换为整数求和。我的代码:
ch = ["+7", "-3", "+10", "0"]
ch.to_i
soma = 0
string.each do |ch|
if ch.isdigit()
soma += ch.to_i
end
end
p(soma)
错误:
Traceback (most recent call last):
main.rb:2:in `<main>': undefined method `to_i' for ["+7", "-3", "+10", "0"]:Array (NoMethodError)
Did you mean? to_s
to_a
to_h
解决方案
而不是调用to_i
这一行中的字符串数组,ch.to_i
您需要调用to_i
数组中的每个元素,如下所示:
numbers = ["+7", "-3", "+10", "0"]
sum = 0
numbers.each do |element|
sum += element.to_i
end
puts sum
#=> 14
或者简化并使用常见的 Ruby 习惯用法:
numbers = ["+7", "-3", "+10", "0"]
numbers.map(&:to_i).sum
#=> 14
推荐阅读
- json - 使用 jq 将 JSON {"k1":"v1","k2":"v2"} 转换为 CSV: v1,v2
- github-api - Github API:如何获取已为 repo 加注星标并克隆它的用户列表
- java - Java - 在使用随机获取文本文件中的行时尝试避免重复
- php - 使用 PHP 在 WordPress 站点中搜索字符串并替换为新字符串
- laravel - 数据透视表中的 detach()
- python-3.x - ReadProcessMemory 无效句柄
- amazon-web-services - AWS S3 Cloudormation 更新堆栈失败
- python - Python:venn3_circles:如何在 Venn 3 圆图中获取交点的值
- python-3.x - 如何在while循环后将变量重置为初始值
- javascript - 在基于 typescript 的项目中使用 Vue js 组件