2

I have tried:

elsif file.grep(/Mode: 1/)
   puts "test"
else
   puts "test but else" 

Codacy is saying this is wrong. Is there a way to improve this? According to Codacy:

unexpected token kELSIF (Using Ruby 2.2 parser; configure using `TargetRubyVersion` parameter, under `AllCops`)

unexpected token kELSE (Using Ruby 2.2 parser; configure using `TargetRubyVersion` parameter, under `AllCops`)
4
  • 1
    it should start with if, not elsif Commented Mar 26, 2019 at 17:56
  • 1
    And it should end with end. Commented Mar 26, 2019 at 18:06
  • 1
    And grep is Enumerable method. Commented Mar 26, 2019 at 18:23
  • 2
    Possible duplicate of What's the best way to search for a string in a file? Commented Mar 26, 2019 at 20:46

1 Answer 1

4

You can use IO::read to assign text file content and then String#include? for checking.

file_string = File.read('path/to/file')

if file_string.include?('substring')
  puts 'Yes'
else
  puts 'No'
end

Also you can replace it by String#match? (it is faster).

file_string.match?(/pattern/) will return true or false.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much! you're a true lifesaver. I'm new to ruby, and this helps loads. Thank you!
Glad I could help
if I want to print something from file it shows blank output even though condition is true as the text matches File.open("fahad.txt","r") do |i| if i.read().include?("major") puts i.read() end end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.