根据符号 Ruby 更新数组
updating array based on symbols Ruby
如何根据符号更新数组?喜欢
data = []
string = "Hello"
if( !data.include? string )
count += 1
data.insert(-1, {
label: string,
value: count,
})
else
#logic to change count value if string is encountered again
end
我正在考虑找到字符串所在的索引,然后删除它以在该索引处插入另一个更新的值。这是正确的方法吗?
只需使用 find
即可获得匹配项,前提是它在数组中是唯一的。您可以使用 select
来获得多个匹配项。之后只需更新计数
由于您的示例断章取义且包含错误,我冒昧地做了一个更完整的示例。
data = []
strings = ["Hello", "Bye", "Hello", "Hi"]
strings.each do |string|
hash = data.find{ |h| h[:label] == string }
if hash.nil?
data << {label: string, value: 1}
else
hash[:value] += 1
end
end
如何根据符号更新数组?喜欢
data = []
string = "Hello"
if( !data.include? string )
count += 1
data.insert(-1, {
label: string,
value: count,
})
else
#logic to change count value if string is encountered again
end
我正在考虑找到字符串所在的索引,然后删除它以在该索引处插入另一个更新的值。这是正确的方法吗?
只需使用 find
即可获得匹配项,前提是它在数组中是唯一的。您可以使用 select
来获得多个匹配项。之后只需更新计数
由于您的示例断章取义且包含错误,我冒昧地做了一个更完整的示例。
data = []
strings = ["Hello", "Bye", "Hello", "Hi"]
strings.each do |string|
hash = data.find{ |h| h[:label] == string }
if hash.nil?
data << {label: string, value: 1}
else
hash[:value] += 1
end
end