class ::Hash # via https://stackoverflow.com/a/25835016/2257038 defstringify_keys h = self.map do |k,v| v_str = if v.instance_of? Hash v.stringify_keys else v end
[k.to_s, v_str] end Hash[h] end
# via https://stackoverflow.com/a/25835016/2257038 defsymbol_keys h = self.map do |k,v| v_sym = if v.instance_of? Hash v.symbol_keys else v end
# We want to get both {{mustache_template}}, and a normal substitution { like_this }, but not a { {{ crazy_one }} }
text = "We want to get both {{mustache_template}}, and a normal substitution {like_this}, but not a { {{ crazy_one }} }" p text.scan(/\{{1,2}([^{}]+)\}{1,2}[^}]/) # [["mustache_template"], ["like_this"]]
Create a directory ‘Log/’ whith 10 log files named log0.txt, log1.txt, … ,etc. Each of which prints hello\n world\n #{ file_name }
And then read from eatch file, and append them into array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Dir.mkdir('Log') Dir.chdir('Log') 10.times.each do |i| file_name = "log#{i}.txt" File.open(file_name, 'w') do |f| f.puts 'hello' f.puts 'world' f.puts file_name end end
res = Dir.glob('Log/*.txt').each_with_object([]) do |file_name, ret| ret.push(*File.readlines(file_name)) end
Modify the BankAccount class to make it comparable based on the account banlance
Create Bank has instance variable accounts and make it enumerable based on the accounts
Using 50 threads to create 200 accounts, and deposit each with a random amounts of money and store them into one file: ‘balance.txt’. Each line of balance.txt is account information for each account. e.g.
Time.now.to_s 100
Time.now.to_s 32
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
bank = Bank.new([]) File.open('balance.txt', 'a') do |f| threads = [] 50.times do |i| threads[i] = Thread.new do 4.times do |j| account = BankAccount.new() account.deposit(rand(100)) bank.add(account) f.puts "#{i}#{Time.now.to_s}#{account.balance}" f.flush end end end # threads.each{ |t| t.join } threads.each(&:join) end bank.each { |e| puts e}