Tag: key

如何从MongoDB打印所有键和值?

例如,我有一个集合中的记录: { “_id” : ObjectId(“4f0224ad6f85ce027e000031”), “monday” : “7am” } { “_id” : ObjectId(“4f0224ad6f85ce027e00002e”), “tuesday” : “11.40am” } { “_id” : ObjectId(“4f0224ad6f85ce027e000025”), “wednestay” : “12am”, “thursday” : “1pm” } 在控制器中,我将抓住所有项目,在视图中我想在形状中打印它们: monday 7am tuesday 11.40am wednesday 12am thursday 1pm 我的应用程序正在Rails上运行。 存在任何快速和优雅的方式吗? 谢谢! 编辑这对我有用 : records = collection.where(‘something’ => variable) records.each do |rec| puts rec._id end 这不是 records […]

在Ruby中将嵌套的哈希键从CamelCase转换为snake_case

我正在尝试构建一个API包装器gem,并且在从API返回的JSON中将哈希键转换为更多Rubyish格式时遇到问题。 JSON包含多层嵌套,包括哈希和数组。 我想要做的是递归地将所有键转换为snake_case以便于使用。 这是我到目前为止所得到的: def convert_hash_keys(value) return value if (not value.is_a?(Array) and not value.is_a?(Hash)) result = value.inject({}) do |new, (key, value)| new[to_snake_case(key.to_s).to_sym] = convert_hash_keys(value) new end result end 上面调用此方法将字符串转换为snake_case: def to_snake_case(string) string.gsub(/::/, ‘/’). gsub(/([AZ]+)([AZ][az])/,’\1_\2′). gsub(/([az\d])([AZ])/,’\1_\2′). tr(“-“, “_”). downcase end 理想情况下,结果类似于以下内容: hash = {:HashKey => {:NestedHashKey => [{:Key => “value”}]}} convert_hash_keys(hash) # => {:hash_key => {:nested_hash_key […]