In Ruby, what would be the equivalent of the Python code below?
在Ruby中,下面的Python代码相当于什么?
x = [6, 7, 8, 9, 10, 2, 3, 4]
y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
min(range(len(x)), key=lambda i: y.index(x[i]))
=> 5
Edit: I'm just looking for a direct translation from Python to Ruby, don't bother about the semantic of the provided example.
编辑:我只是在寻找从Python到Ruby的直接翻译,不要理会所提供示例的语义。
2 个解决方案
#1
1
Translating directly...
直接翻译......
(0...x.length).min_by { |i| y.find_index(x[i]) }
Built-in functions that take lambdas in python tend to translate to Ruby methods that take blocks (lambdas defined in-line, essentially).
在python中使用lambdas的内置函数倾向于转换为带有块的Ruby方法(lambda基本上是在线定义的)。
Edit: A slightly more idiomatic translation could be
编辑:稍微更惯用的翻译可能是
obj,index = x.each_with_index.min_by { |o,i| y.find_index(o) }
index
#2
2
Do you want to get the index of the smallest element?
你想获得最小元素的索引吗?
x = [6, 7, 8, 9, 10, 2, 3, 4]
x.index(x.min()) # => 5
x.each_with_index.min[1] # => 5
(0...x.size).min_by {|i| x[i] } # => 5
#1
1
Translating directly...
直接翻译......
(0...x.length).min_by { |i| y.find_index(x[i]) }
Built-in functions that take lambdas in python tend to translate to Ruby methods that take blocks (lambdas defined in-line, essentially).
在python中使用lambdas的内置函数倾向于转换为带有块的Ruby方法(lambda基本上是在线定义的)。
Edit: A slightly more idiomatic translation could be
编辑:稍微更惯用的翻译可能是
obj,index = x.each_with_index.min_by { |o,i| y.find_index(o) }
index
#2
2
Do you want to get the index of the smallest element?
你想获得最小元素的索引吗?
x = [6, 7, 8, 9, 10, 2, 3, 4]
x.index(x.min()) # => 5
x.each_with_index.min[1] # => 5
(0...x.size).min_by {|i| x[i] } # => 5