ruby/rails file get line number

# Step 1: Define the method to get line number
def get_line_number(file_path, target_text)
  # Step 2: Check if the file exists
  unless File.exist?(file_path)
    puts "File not found: #{file_path}"
    return nil
  end

  # Step 3: Read the file line by line
  File.foreach(file_path).with_index do |line, line_number|
    # Step 4: Check if the target text is present in the current line
    return line_number + 1 if line.include?(target_text)
  end

  # Step 5: Return nil if the target text is not found in the file
  puts "Target text not found in #{file_path}"
  nil
end

# Example Usage:
file_path = 'path/to/your/file.rb'
target_text = 'your_target_text'
line_number = get_line_number(file_path, target_text)

# Step 6: Output the result
puts "Line number of '#{target_text}' in #{file_path}: #{line_number}"