gpt4 book ai didi

ruby 数组将 first,second 放入变量,其余放入另一个变量

转载 作者:数据小太阳 更新时间:2023-10-29 06:47:51 24 4
gpt4 key购买 nike

我想把一个数组分成三个变量;第一个值放入一个变量,第二个值放入另一个变量,其余所有放入一个字符串,例如:

arr = ["a1","b2","c3","d4","e5","f6"]
var1 = arr[0] # var1 => "a1"
var2 = arr[1] # var2 => "b2"
var3 = ? # var3 should be => "c3d4e5f6"

需要什么代码来实现每个变量的列出值?

最佳答案

这看起来和任何东西一样好:

arr = ["a1","b2","c3","d4","e5","f6"]
var1 = arr[0] # => "a1"
var2 = arr[1] # => "b2"
var3 = arr[2..-1].join # => "c3d4e5f6"

如果你不需要保留arr,你可以这样做:

arr = ["a1","b2","c3","d4","e5","f6"]
var1 = arr.shift # => "a1"
var2 = arr.shift # => "b2"
var3 = arr.join # => "c3d4e5f6"

别人都在指出splat运算符,可以理解,但我觉得这个比上面的还差:

arr = ["a1","b2","c3","d4","e5","f6"]
var1, var2, *tmp = arr
var3 = tmp.join

是这样的:

arr = ["a1","b2","c3","d4","e5","f6"]
var1, var2, *var3 = arr
var3 = var3.join

不过,这是一个需要注意的选项。

关于ruby 数组将 first,second 放入变量,其余放入另一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16929814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com