How to check whether a string contains a substring in Ruby

I have a string variable with content: varMessage = “hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n” “/my/name/is/balaji.so\n” “call::myFunction(int const&)\n” “void::secondFunction(char const&)\n” . . . “this/is/last/line/liobrary.so” In the string I have to find a sub-string: “hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n” “/my/name/is/balaji.so\n” “call::myFunction(int const&)\n” How can I find it? I need to determine whether the sub-string is present or not. 9 s 9 You can use the … Read more

What does %w(array) mean?

I’m looking at the documentation for FileUtils. I’m confused by the following line: FileUtils.cp %w(cgi.rb complex.rb date.rb), ‘/usr/lib/ruby/1.6′ What does the %w mean? Can you point me to the documentation? 8 s 8 %w(foo bar) is a shortcut for [“foo”, “bar”]. Meaning it’s a notation to write an array of strings separated by spaces instead … Read more

Why is it bad style to `rescue Exception => e` in Ruby?

Ryan Davis’s Ruby QuickRef says (without explanation): Don’t rescue Exception. EVER. or I will stab you. Why not? What’s the right thing to do? 6 s 6 TL;DR: Use StandardError instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception is probably okay. Exception … Read more

What is attr_accessor in Ruby?

I am having a hard time understanding attr_accessor in Ruby. Can someone explain this to me? 20 s 20 Let’s say you have a class Person. class Person end person = Person.new person.name # => no method error Obviously we never defined method name. Let’s do that. class Person def name @name # simply returning … Read more

How to convert a string to lower or upper case in Ruby

How do I take a string and convert it to lower or upper case in Ruby? 1 11 Ruby has a few methods for changing the case of strings. To convert to lowercase, use downcase: “hello James!”.downcase #=> “hello james!” Similarly, upcase capitalizes every letter and capitalize capitalizes the first letter of the string but … Read more