当使用 ruby 定义一系列键时,将所有键值作为组合字符串获取
Get all the Key values as a combined string when a range of keys are defined using ruby
我有以下代码
class MyClass
def my_method(first,last)
#this should take 2 numbers as arguments and should return the keys value(s) as a combined string
end
private
def lines_of_code
{
1 => "This is first",
2 => "This is second",
3 => "This is third",
4 => "This is fourth",
5 => "This is fifth"
}
end
m = MyClass.new
m.my_method(2,4) # This is secondThis is thirdThis is fourth"
我应该将一个范围传递给 my_method,然后 return 我应该将组合值字符串传递给我。
对不起,如果这已经发布了。
提前致谢。
这是一个使用 Hash#values_at
的技巧:
class MyClass
def my_method(first, last)
lines_of_code.values_at(*first..last)
end
private
def lines_of_code
{
1 => "This is first",
2 => "This is second",
3 => "This is third",
4 => "This is fourth",
5 => "This is fifth"
}
end
end
m = MyClass.new
p m.my_method(2,4)
# >> ["This is second", "This is third", "This is fourth"]
# to get a string
p m.my_method(2,4).join(" ")
# >> "This is second This is third This is fourth"
lines_of_code.values_at(*first..last).join
我有以下代码
class MyClass
def my_method(first,last)
#this should take 2 numbers as arguments and should return the keys value(s) as a combined string
end
private
def lines_of_code
{
1 => "This is first",
2 => "This is second",
3 => "This is third",
4 => "This is fourth",
5 => "This is fifth"
}
end
m = MyClass.new
m.my_method(2,4) # This is secondThis is thirdThis is fourth"
我应该将一个范围传递给 my_method,然后 return 我应该将组合值字符串传递给我。 对不起,如果这已经发布了。
提前致谢。
这是一个使用 Hash#values_at
的技巧:
class MyClass
def my_method(first, last)
lines_of_code.values_at(*first..last)
end
private
def lines_of_code
{
1 => "This is first",
2 => "This is second",
3 => "This is third",
4 => "This is fourth",
5 => "This is fifth"
}
end
end
m = MyClass.new
p m.my_method(2,4)
# >> ["This is second", "This is third", "This is fourth"]
# to get a string
p m.my_method(2,4).join(" ")
# >> "This is second This is third This is fourth"
lines_of_code.values_at(*first..last).join