简体   繁体   English

Ruby-更优雅地推向数组

[英]Ruby - more elegant pushing to array

valrow = [ 0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
lblrow = [48,  8539,  188,  8540, 189,  8541,  190,  8542]
opts = []
(0..7).each {|i| opts.push([lblrow[i].chr(Encoding::UTF_8), valrow[i]]) }

What is the most elegant way to do this? 最优雅的方法是什么?

Use Array#zip 使用Array#zip

valrow = [ 0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
lblrow = [48,  8539,  188,  8540, 189,  8541,  190,  8542]
opts = lblrow.map { |c| c.chr(Encoding::UTF_8) }.zip(valrow)

Or use collect.with_index : 或使用collect.with_index

valrow = [ 0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
lblrow = [48,  8539,  188,  8540, 189,  8541,  190,  8542]
opts = valrow.collect.with_index { |val,index| [lblrow[index].chr(Encoding::UTF_8), val] }

You can use an Enumerator object in this case: 在这种情况下,可以使用Enumerator对象:

value_enum = valrow.to_enum
opts = lblrow.map { |item| [item.chr(Encoding::UTF_8), value_enum.next] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Ruby on Rails中推送到数组 - Pushing to an Array in Ruby on Rails 在Ruby中,有一种替代的,更优雅的方法来调用方法而不是'case - when'吗? - In Ruby is there an alternative and more elegant way to call a method than 'case - when'? 有没有更优雅的方法来执行多重包含? 选择红宝石? - Is there a more elegant way to perform a multiple include? selection in ruby? Haml:编写标签+ ruby​​-expression +字符串的更优雅的方式 - Haml: more elegant way to write tag + ruby-expression + string 将多维数组的元素推入Ruby中的另一个数组 - Pushing elements of a multidimensional array into another one in Ruby Ruby 中最优雅的替换“?”的方法是什么? 在字符串中,值在数组中 - What is the most elegant way in Ruby to substitute '?' in string with values in array 在Ruby中将最大散列键值推入数组? - Pushing max hash key-values into an array in Ruby? 如何简化将多个值推入Ruby中的数组? - How do I simplify pushing multiple values into an array in Ruby? Ruby on Rails以更优雅的方式来验证用户只能编辑自己的内容 - Ruby on rails more elegant way to authenticate that users can edit only their own content 在Ruby中加快Date#parse和Date#strptime的速度,采用更优雅的方式还是最佳实践? - Speed up Date#parse & Date#strptime in Ruby, more elegant way or best practice?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM