Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Try updating a portion of a yaml file
f = File.open("./example.yaml", "w")
100000.times do |n|
str = "user_#{n}:\n id: #{n}\n score: 0\n"
File.write("./example.yaml", str, mode: "a")
end
def find_position(target, file_obj)
file_obj.pos = file_obj.read =~ Regexp.new(target)
end
def update_user(name, params)
file = File.new("./example.yaml")
char_pos = find_position(name, file)
new_str = 3.times.with_object("") do |_, str|
str << file.readline
end
params.each do |k, v|
attr_line = Regexp.new(k.to_s + ".+$")
new_str.sub!(attr_line, "#{k}: #{v}")
end
File.write("./example.yaml", new_str, char_pos)
end
require 'yaml'
def modify_user(name, params)
users_info = YAML.load_file("./example.yaml")
user = users_info[name]
params.each do |k, v|
user[k.to_s] = v
end
File.open("./example.yaml", "w") do |f|
f.write(YAML.dump(users_info))
end
end
def change_user(name, params)
users_info = YAML.load_file("./example.yaml")
user_info = users_info[name]
params.each do |k, v|
user_info[k.to_s] = v
end
pos = find_position(name, File.open("./example.yaml"))
user_hash = { name => user_info }
File.write("./example.yaml", YAML.dump(user_hash).sub("---\n", ""), pos)
end
start = Time.new
update_user("user_500000", score: 9)
over = Time.new
duration = over - start
p duration
start = Time.new
modify_user("user_500000", score: 8)
over = Time.new
duration = over - start
p duration
start = Time.new
change_user("user_500000", score: 7)
over = Time.new
duration = over - start
p duration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment