Charles Charles - 7 months ago 10
Ruby Question

How to read a specific element from a certain user

I'm having problems with this code:

if @msg =~ /!myxp/i
file = File.open("myxp.txt") do |record|
record.each do |item|
id, xp, name = item.chomp.split(', ')
puts "#{name}, your ID is #{id} and you have #{xp}XP!"
end
end


My
myxp.txt
has:

6753, 50, User1
58763, 30, User2
90845, 80, User3


User2
says !myxp and it sends all of the other ones, too (User1 and User3).

How do I make it only works for User2 instead of everyone?

Answer

If you're looking to isolate the XP value for a particular user you need to narrow it down using a filter or a condition:

case (@msg.downcase)
when /!myxp/
  File.open("myxp.txt") do |record|
    record.each do |item|
      id, xp, name = item.chomp.split(', ')

      # Skip this entry unless name matches my name
      next unless (name == @name)

      puts "#{name}, your ID is #{id} and you have #{xp}XP!"
    end
  end
end

I've taken the liberty of switching your if that tests commands into a case because this makes adding other commands simple and keeps things organized.

I'm not sure where the person's name is stored, so it's @name in this example.