Get all the Key values as a combined string when a

2019-08-15 06:52发布

I have the following code

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"

I should pass a range to my_method that inturn should return me the combined value string. Sorry if this is already posted.

Thanks in advance.

标签: ruby string hash
2条回答
一夜七次
2楼-- · 2019-08-15 07:00

Here is a trick using 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"
查看更多
老娘就宠你
3楼-- · 2019-08-15 07:25
lines_of_code.values_at(*first..last).join
查看更多
登录 后发表回答