ruby - 当使用 ruby​​ 定义一系列键时,将所有键值作为组合字符串获取

标签 ruby string hash

我有以下代码

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,它反过来应该返回组合值字符串。 抱歉,如果这已经发布。

提前致谢。

最佳答案

这是一个使用 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"

关于ruby - 当使用 ruby​​ 定义一系列键时,将所有键值作为组合字符串获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27835569/

相关文章:

ruby - 在 Sinatra 中,生产环境和开发环境有什么区别?

ruby-on-rails - 我在哪里可以阅读有关 ruby​​ on rails 中的 REST 的信息?

c++ - 如何推送字符数组?

c++ - 在 C++ 中使用数组创建哈希表表示

java - 为什么我的哈希函数收到负值?

java - 在 HashMap 中查找第一、第二、第三最小值

ruby-on-rails - 使用 ActiveRecord 总和进行排序和限制?

ruby-on-rails - 如何更改 Rails 3 Controller 中 View 文件的默认路径?

java - 使用堆栈来反转字符串?

java - 如何知道给定字符串是否是Java中另一个字符串的子字符串