简体   繁体   English

Ruby在“ do”循环中使用哈希

[英]Ruby use hash in 'do' loop

I have a code which looks like this: 我有一个看起来像这样的代码:

hash = {
     1000 => "john",
     1001 => "mary",
}

list = File.foreach("list.txt").map { |line| line.split('  ') }

out = list.each do |(file, user, time)|
     puts "Some plain text #{file}, #{user}, #{time}"
end

In #{user} I get a number which can be 1000 or 1001. 在#{user}中,我得到的数字可以是1000或1001。

My question is, how can I access info from hash to be able to put it instead of #{user}. 我的问题是,如何才能从哈希访问信息,而不是#{user}。 In my understanding final output should look like this. 以我的理解,最终输出应如下所示。

Some plain text, file.txt, john, 00:00 一些纯文本,file.txt,约翰,00:00

I was thinking about doing it like this, but it didn't worked. 我当时正在考虑这样做,但没有成功。

puts "Some plain text #{file}, hash[user], #{time}"

使用字符串插值(就像您对filetime所做的那样),它适用于任何有效的Ruby表达式。

puts "Some plain text #{file}, #{hash[user]}, #{time}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM