本帖最后由 zlyl_wiley 于 2023-7-27 21:37 编辑
File .open ( 'address.txt' , 'w' ) { |f| f.write "name=阿尔西斯\n phone_number=15915915159\n " }
# values的[0]是值的起始位置,[1]是占用长度,先自己掰手指头算好
$pos = { :name => [ 5 , 12 ] , :number => [ 32 , 11 ] }
def save_to_file( key, value)
s = value + " " * ( $pos[ key] [ 1 ] - value.length )
File .open ( 'address.txt' , 'r+' ) do |file|
file.seek ( $pos[ key] [ 0 ] )
file.write ( s)
end
end
def load_from_file( key)
File .open ( 'address.txt' , 'r' ) do |file|
file.seek ( $pos[ key] [ 0 ] )
return file.gets
end
end
# 字符串才strip,因为to_i已有同样效果
p $name = load_from_file( :name ) .strip # => "阿尔西斯"
p $number = load_from_file( :number ) .to_i # => 15915915159
$name = "艾里克"
$number = 10086
save_to_file( :name , $name )
save_to_file( :number , $number .to_s )
p $name2 = load_from_file( :name ) .strip # => "艾里克"
p $number2 = load_from_file( :number ) .to_i # => 10086
File .open ( 'address.txt' , 'w' ) { |f| f.write "name=阿尔西斯\n phone_number=15915915159\n " }
# values的[0]是值的起始位置,[1]是占用长度,先自己掰手指头算好
$pos = { :name => [ 5 , 12 ] , :number => [ 32 , 11 ] }
def save_to_file( key, value)
s = value + " " * ( $pos[ key] [ 1 ] - value.length )
File .open ( 'address.txt' , 'r+' ) do |file|
file.seek ( $pos[ key] [ 0 ] )
file.write ( s)
end
end
def load_from_file( key)
File .open ( 'address.txt' , 'r' ) do |file|
file.seek ( $pos[ key] [ 0 ] )
return file.gets
end
end
# 字符串才strip,因为to_i已有同样效果
p $name = load_from_file( :name ) .strip # => "阿尔西斯"
p $number = load_from_file( :number ) .to_i # => 15915915159
$name = "艾里克"
$number = 10086
save_to_file( :name , $name )
save_to_file( :number , $number .to_s )
p $name2 = load_from_file( :name ) .strip # => "艾里克"
p $number2 = load_from_file( :number ) .to_i # => 10086
这样能快一点么……