0

I have this code:

on :message, "something" do |m|
  m.reply file.read.lines[2]
end

...which works, but only once. When I try it again or use the same code but with a different file, it doesn't work. Can someone help me do this?

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
EPICBRONY
  • 45
  • 6

1 Answers1

0

The reason you're getting this behavior depends on how you're defining file.

But with no other information it's still possible to give a (hopefully) working example:

on :message, "something" do |m|
  first_line_to_read = 0
  last_line_to_read = 2
  lines_of_text = file.read.split("\n")
  first_line_to_read.upto(last_line_to_read).each do |idx|
    m.reply lines_of_text[idx]
  end
end

Hopefully this example is clear. It sends separate replies for each line of the text that is within the bounds of the first_line_to_read and last_line_to_read indexes.

Some important concepts are:

  • Read the entire file into a string and store it to a variable. If for whatever reason you can't call file.read multiple times, this will store the result of calling it the first time.
  • Split the string by newlines
  • Use an iterator to go one-by-one through the desired lines of text
  • inside the iterator block, use the m variable which is defined in parent scope to send the message.
max pleaner
  • 26,189
  • 9
  • 66
  • 118