简体   繁体   中英

Ruby:-Find the occurrences of a character in a file

I am looking for the Ruby method that can help me find the occurrences of a character in a file.I am looking for all occurrences, not just the first one.

I am able to read the file with the help of File.read("filename") .

I do know how to find the no of occurrence in a particular string but dont know how to implement it when finding the characters in the file.

Please help.

Using File.read("filename") is not the most efficient way to do it, but it does not matter unless the file is too big, and if you are using it anyway, then File.read("filename") is indeed a string, so do it as you would with other strings.

File.read("filename").count(some_character)

or

File.new("filename").each_char.inject(0){|n, c| n += 1 if c == some_character; n}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM