Ruby - String String Expressions

Introduction

Using the + symbol concatenates the two strings "Test" and "String" to produce "TestString".

Demo

puts "Success!" if "Test" + "String" == "TestString"

Result

You can multiply strings.

For example, let's say you want to replicate a string five times, like so:

Demo

puts "abc" * 5

Result

You can also perform "greater than" and "less than" comparisons:

Demo

puts "x" > "y" 
puts "y" > "x"

Result

"x" > "y" and "y" > "x" are expressions that result in true or false outcomes.

In this situation, Ruby compares the numbers that represent the characters in the string.

To learn what value a particular character has, find out like so:

Demo

puts ?x 
puts ?A

Result

A question mark followed by a character returns an integer matching the position of that character in the ASCII table.

You can achieve the inverse by using the String class's chr method. For example:

Demo

puts ?x 
puts 120.chr

Result

Related Topic