0

我正在使用 Ruby on Rails 3.2.2。我有以下情况:

# hash_params.class
# => Hash
# hash_params.inspect
# => { :key1 => :value1, :key2 => value2, ... => ... }
#
def self.method_1(hash_params)
  hash_params.each do { |hash_param| self.method_2(hash_param) }
end

# param.class
# => Array
# param.inspect
# => [:key1, value1] # or '[:key2, value2]' or '[..., ...]', depending on cases.
# 
def self.method_2(param)
  logger.debug "Key   => #{param[0])"
  logger.debug "Value => #{param[1])"
end

给定上面代码中注释掉的输出,当我method_1在记录器文件中运行 then 时,我有以下内容:

Key   => :key1
Value => :value1
Key   => :key2
Value => :value2
Key   => ...
Value => ...

我想将param变量method_2 视为键/值对而不是数组),例如通过制作如下内容

def self.method_2(param)
  param do |key, value| # Note: This code line doesn't work. It is just a sample code to clarify the question.
    logger.debug "Key   => #{key.inspect)"
    logger.debug "Value => #{value.inspect)"
  end
end

? 是否可以?如果是这样,怎么做?你有什么建议?

4

2 回答 2

2

使用Hash[]

param = [:key1, 'value1']
h = Hash[*param]
puts h[:key1]

输出:

价值1

于 2012-09-21T05:41:18.360 回答
0

怎么样

def self.method_1(hash_params)
  hash_params.each do { |key, value| self.method_2(key, value) }
end

def self.method_2(key, value)
  logger.debug "Key   => #{key)"
  logger.debug "Value => #{value)"
end

否则,您仍然可以在参数中传递哈希,例如

def self.method_1(hash_params)
  hash_params.keys.each do { |key| self.method_2(hash_params.slice(key)) }
end

编辑:如果你想要一个哈希作为参数,你可以这样做

def self.method_1(hash_params)
  hash_params.each do { |key, value| self.method_2({key => value}) }
end
于 2012-09-21T05:32:59.413 回答