I've been struggling with this: Complete the keysAndValues function so that it takes in an object and returns the keys and values as separate arrays.
我一直在努力解决这个问题:完成keysAndValues函数,以便它接收一个对象并将键和值作为单独的数组返回。
I've added several versions so you can see how i'm thinking through the problem.
我添加了几个版本,所以你可以看到我是如何思考这个问题的。
def keysAndValues(data)
data.each do |data|
data.split(key.to_a, value.to_a)
end
data
end
keysAndValues ({a: 1, b: 2, c: 3})
def keysAndValues(data)
data.each do |data|
data.split([key], [value])
end
data
end
keysAndValues ({a: 1, b: 2, c: 3})
def keysAndValues(data)
data.each do |data|
data.slice([key], [value])
end
data
end
keysAndValues ({a: 1, b: 2, c: 3})
def keysAndValues(data)
data.each do |data|
data.slice_to.a(2)([ :a ], [ ' ' ])
end
data
end
keysAndValues ({a: 1, b: 2, c: 3})
def keysAndValues(data)
data.each.slice_to.a(2) { |x, y| [x], [y] }
end
data
end
keysAndValues ({a: 1, b: 2, c: 3})
3 个解决方案
#1
2
def keysAndValues(data)
[data.keys, data.values]
end
keys, values = keysAndValues({a: 1, b: 2, c: 3})
keys
# => [:a, :b, :c]
values
# => [1, 2, 3]
Please note that keysAndValues
is not following the Ruby naming convention. The correct name should be keys_and_values
.
请注意,keysAndValues不遵循Ruby命名约定。正确的名称应该是keys_and_values。
#2
1
There are built-in methods for that:
有内置的方法:
irb(main):001:0> {a: 1, b: 2, c: 3}.keys
=> [:a, :b, :c]
irb(main):002:0> {a: 1, b: 2, c: 3}.values
=> [1, 2, 3]
Or, maybe you want this? (Sorry, your question is not clear to me)
或者,也许你想要这个? (抱歉,我的问题不明确)
irb(main):003:0> Array({a: 1, b: 2, c: 3})
=> [[:a, 1], [:b, 2], [:c, 3]]
#3
0
def keys_and_values(data)
return data.keys, data.values
end
thus:
从而:
data_hash = {a: 1, b: 2, c: 3, d: 4}
data_hash = {a:1,b:2,c:3,d:4}
keys_and_values(data_hash)
keys_and_values(data_hash)
returns:
收益:
[[a:, b:, c:, d:], [1, 2, 3, 4]]
#1
2
def keysAndValues(data)
[data.keys, data.values]
end
keys, values = keysAndValues({a: 1, b: 2, c: 3})
keys
# => [:a, :b, :c]
values
# => [1, 2, 3]
Please note that keysAndValues
is not following the Ruby naming convention. The correct name should be keys_and_values
.
请注意,keysAndValues不遵循Ruby命名约定。正确的名称应该是keys_and_values。
#2
1
There are built-in methods for that:
有内置的方法:
irb(main):001:0> {a: 1, b: 2, c: 3}.keys
=> [:a, :b, :c]
irb(main):002:0> {a: 1, b: 2, c: 3}.values
=> [1, 2, 3]
Or, maybe you want this? (Sorry, your question is not clear to me)
或者,也许你想要这个? (抱歉,我的问题不明确)
irb(main):003:0> Array({a: 1, b: 2, c: 3})
=> [[:a, 1], [:b, 2], [:c, 3]]
#3
0
def keys_and_values(data)
return data.keys, data.values
end
thus:
从而:
data_hash = {a: 1, b: 2, c: 3, d: 4}
data_hash = {a:1,b:2,c:3,d:4}
keys_and_values(data_hash)
keys_and_values(data_hash)
returns:
收益:
[[a:, b:, c:, d:], [1, 2, 3, 4]]