Reputation: 385
I want to have the code to overwrite existing names when the score is higher than the current in the file.
The file looks like the following: https://i.sstatic.net/LuQwp.png This is the code:
def highscore(name,score)
a = File.new("highscore.txt", "w")
if @Bestenliste.include?("#{name}")
x = @Bestenliste.index("#{name}")
@Bestenliste.delete_at(x)
end
@Bestenliste = @Bestenliste + [name.to_s + "," + score.to_s]
a.puts @Bestenliste
a.close
end
Problem is, that the name and the points in the array are not seperate, and if i want to change that I need to change my whole program. Can I somehow use wildcards or something like that on the name, and also compare the score at the same time ?
I want to overwrite a specific name when it already exists and the score is higher
Upvotes: 1
Views: 144
Reputation: 322
So you want to use a regex to search through your array and replace a specific index if found? Check this post, about using regex to search through an array. I think you should be able to make use Mladen Jablanović's answer there. You can read up on how to use Ruby String's =~ regex matcher here.
I think that you could accomplish it via
x = @Bestenliste.index{|e| e =~ /#{Regexp.quote(name)}.*/ }
unless x.nil?
@Bestenliste.delete_at(x)
end
@Bestenliste = @Bestenliste + [name.to_s + "," + score.to_s]
I used this to create and test the regex, and this stackoverflow post for the string interpolation.
Upvotes: 0
Reputation: 90
I think that your program will be more efficient if you move the data to a hash instead of an array.
array.each {|set| set.split(",")}
array=array.to_h
Then you can easily just compare values and replace.
if num > array[name]
array[name]=num
end
The alternative as far as I am aware would be for you to split the value when you are comparing. I don't actually see any comparison in your program. Something like
@Bestenlite.split(",")
if @Bestenliste[0]==name
if @Bestenliste[1].to_i<score
something like that, but that is going to heavily complicate your code.
Upvotes: 1