How to Compare Strings in Ruby

Save

Ruby is an extremely powerful programming/scripting language. With powerful capabilities and an efficient syntax, many things are possible with Ruby. This article explains how to compare the text that is stored in string variables in Ruby.

Things You'll Need

  • Ruby interpreter
  • Keyboard
  • Open up any text editor, such as notepad or SciTE. We are going to compare two strings using simple equality comparison.

  • Type in the following code:

    s = "This is my string."
    s2 = "This is my other string."

    puts s.eql?(s2)

  • The first thing we do above is assign a value to the string 's' and then a different value to the string s2. The first line beginning with puts will print out "false" because it runs a basic equality test on the two strings. These strings are not equal, so it prints false.

  • Save your program as 'myprogram.rb' and open up a command line prompt. Change to the directory where you saved your program and type 'ruby myprogram.rb' to see the output.

Promoted By Zergnet

Comments

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!