获取数组中三个连续元素的值
我有一个大数组 h
,其中包含名为 startingParam
的参数的多个实例,该参数后面总是跟着两个相关但并不总是相同的其他参数。我需要查找数组中 startingParam
的每个实例,并将其和接下来的两个参数推入一个单独的数组 holdingArray
中。
由于我对 Ruby 非常陌生,因此以下代码不起作用。有人知道我做错了什么吗?有更好的方法来解决这个问题吗?
h.each do |param|
if param == 'startingParam'
holdingArray << h.[param],
holdingArray << h.[param + 1],
holdingArray << h.[param + 2]
end
end
非常感谢。
I have a large array, h
, that contains several instances of a parameter called startingParam
, which is always followed by two other parameters that are related but not always the same. I need to look for every instance of startingParam
in the array, and push it and the next two parameters into a separate array, holdingArray
.
The following code is not working, due to the fact that I am very new to Ruby. Does anybody know what I am doing wrong? Is there a better way to approach the problem?
h.each do |param|
if param == 'startingParam'
holdingArray << h.[param],
holdingArray << h.[param + 1],
holdingArray << h.[param + 2]
end
end
Thanks so much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用#slice_before 获取块:但是,
如果您创建了原始数据结构,则可能需要重新考虑您的设计。
You can grab the chunks using
#slice_before
:If you created the original data structure, you may want to re-consider your design, however.
功能方法:
Functional approach:
所以存在一些问题。对于初学者来说,您不能通过执行
h.[anything]
来为数组添加下标,而且您还根据值(而不是索引)来下标。您还要检查参数是否与文字字符串“starting_param”匹配,而不是其值。所以我期望你想要的是以下内容:你还会注意到,如果该项目位于数组的最后两个插槽中,这将环绕并从数组的开头抓取项目(由于 Ruby 处理数组下标的方式)超出范围)。
So there are a few problems. For starters, you can't subscript arrays by doing
h.[anything]
, and you are also subscripting based on the value (and not the index). You are also checking to see if the parameter matches the literal string "starting_param" and not its value. So what I expect you want is the following:You'll also note that if the item is in the last two slots of the array, this will wrap around and grab items from the beginning of the array (due to how Ruby handles array subscripts being out of bounds).
您还可以使用范围切片操作(我稍微更改了变量名,因为驼峰式在 ruby 中是不好的风格)
You could also use the range slicing operation (I've changed the varnames slightly since camelcasing is bad style in ruby)