How to get current file and line number in Ruby?
You'll have to use caller
def mylog(str)
caller_line = caller.first.split(":")[1]
puts "#{__FILE__} : #{caller_line} : #{str}"
end
You'll probably want to know the file from which mylog
was called too...
def mylog(str)
caller_infos = caller.first.split(":")
puts "#{caller_infos[0]} : #{caller_infos[1]} : #{str}"
end
Ruby - Read file and print line number
Ruby, like Perl, has the special variable $.
which contains the line number of a file.
File.open("file.txt").each do |line|
puts line, $.
end
Prints:
#Hello
1
#My name is John Smith
2
#How are you?
3
Strip the \n
from line
if you want the number on the same line:
File.open("file.txt").each do |line|
puts "#{line.rstrip} #{$.}"
end
#Hello 1
#My name is John Smith 2
#How are you? 3
As stated in comments, rather than use File.open
you can use File.foreach with the benefit of autoclose at the end of the block:
File.foreach('file.txt') do |line|
puts line, $.
end
# same output...
How do I print the line number of each line in a string?
Slightly modifying your code, try this:
c1.each_line.with_index do |line, index|
puts "line: #{index+1}: #{line}"
end
This uses with with_index
method in Enumerable.
How do I print the line number of the file I am working with via ARGV?
When Ruby's IO class opens a file, it sets the $.
global variable to 0. For each line that is read that variable is incremented. So, to know what line has been read simply use $.
.
Look in the English module for $.
or $INPUT_LINE_NUMBER
.
We can also use the lineno
method that is part of the IO class. I find that a bit more convoluted because we need an IO stream object to tack that onto, while $.
will work always.
I'd write the loop more simply:
File.foreach(ARGV[0]) do |line|
Something to think about is, if you're on a *nix system, you can use the OS's built-in grep
or fgrep
tool to greatly speed up your processing. The "grep" family of applications are highly optimized for doing what you want, and can find all occurrences, only the first, can use regular expressions or fixed strings, and can easily be called using Ruby's %x
or backtick operators.
puts `grep -inm1 abacus /usr/share/dict/words`
Which outputs:
34:abacus
-inm1
means "ignore character-case", "output line numbers", "stop after the first occurrence"
How to Get line number of a word in file using ruby
def get_line_number(file, word)
count = 0
file = File.open(file, "r") { |file| file.each_line { |line|
count += 1
return count if line =~ /#{word}/
}}
end
Advantage of reading line by line is when your file is too large, this wont be heavy on your resources.
Return line number with Ruby readline
Maybe something along these lines:
log_snapshot.each_with_index.reverse_each do |line, n|
case (line)
when /authorization:/
puts '%d: %s' % [ n + 1, line ]
end
end
Where each_with_index
is used to generate 0-indexed line numbers. I've switched to a case
style so you can have more flexibility in matching different conditions. For example, you can add the /i
flag to do a case-insensitive match really easily or add \A
at the beginning to anchor it at the beginning of the string.
Another thing to consider using the block method for File.open
, like this:
File.open(args[:apache_access_log], "r") do |f|
f.readlines.each_with_index.reverse_each do |line, n|
# ...
end
end
Where that eliminates the need for an explicit close
call. The end of the block closes it for you automatically.
Getting current line of code in Ruby
You can use __LINE__
variable. See this https://stackoverflow.com/a/2496240/100466 answer also.
Find line number of key in JSON
Here is the easiest way I found without building your own JSON parser: replace every key entry with unique UUID (alias), then build all combinations of aliases and find that one that returns data from #dig
call
keys = path.split('.')
file_content = File.read(file_path).gsub('null', '1111')
aliases = {}
keys.each do |key|
pattern = "\"#{key}\":"
file_content.scan(pattern).each do
alias_key = SecureRandom.uuid
file_content.sub!(pattern, "\"#{alias_key}\":")
aliases[key] ||= []
aliases[key] << alias_key
end
end
winner = aliases.values.flatten.combination(keys.size).find do |alias_keys|
# nulls were gsubbed above to make this check work in edge case when path value is null
JSON.parse(file_content).dig(*alias_keys).present?
end
file_content.split("\n").take_while { |line| line.exclude?(winner.last) }.count + 1
UPD: The snippet above should not work if JSON value by your foo.bar2
keys is false
. You should gsub
it as well or make this snippet smarter
Related Topics
How to Overwrite the '{ }' Object
Ruby Check Whether Program Is Currently Being Closed
Rails Form_For Never Invokes the Create Controller Action to Use Redirect_To
Perfect Way to Write a Gsub for a Regex Match
How to Set Text Area Properties Inside Controller Page Using Ror
How to Remove Devise Password Resetting During Email Confirmation
Could Not Find 'Cocoapods' (>= 0.A) Among 48 Total Gem(S) (Gem::Missingspecerror)
Count, Size, Length...Too Many Choices in Ruby
Ruby on Rails CSV Upload&Import - File Name Too Long
How to Display a Link to Individual Microposts? (Ruby on Rails 3)
Instantiate Capybara Browser and Set a Proxy
Need Help on Join Table, Limiting Results to Only the Resource Id