Data types in Ruby

Objects in Ruby: Link to heading

In Ruby, everything is an object. Even numbers, strings, and booleans are objects with their own properties and methods.

Example: Link to heading

x = 5 # x is an object of type Integer

x.class # => Integer

x.even? # => true (method that returns a boolean)

Declaration of variables: Link to heading

  • They must begin with a lowercase letter or an underscore (_).
  • It is recommended to use the “snake_case” convention for easy identification.
  • They cannot contain reserved words of the language.

Ruby interprets the words as follows: Link to heading

  1. If there is an equal sign (=) to the right, it is a local variable that is assigned a value.
  2. If it is a reserved word in the language, it fulfills its function.
  3. If none of the above is true, Ruby assumes it is a method.
  4. If an uninitialized local variable is referenced, it is interpreted as a method call with no arguments.

Examples: Link to heading

greeting = "Hello" # Local variable "greeting" with value "Hello"

greeting = 'Hello' # Same value, different type of quotes

greeting = %q(Hello) # Single quotes with interpolation

greeting = %Q(Hello) # Double quotes with interpolation

name = "Pepe"

greeting = "Hello #{name}" # Variable interpolation - "Hello Pepe" if double quotes are used "Hello #{name}" if single quotes are used

greeting.strip # Remove leading and trailing whitespace

greeting.empty? # Check if the variable is empty (returns a boolean)

"Hello world".gsub("Hello", "Hi") # "Hi world" (text replacement method)

Some methods for Strings: Link to heading

  • .upcase: Returns a copy of the string in uppercase.
  • .downcase: Returns a copy of the string in lowercase.
  • .length: Returns the number of characters in the string.
  • .swapcase: Converts uppercase to lowercase and vice versa.
  • .include?: Returns true if the specified character is in the string.
  • .strip: Removes leading and trailing whitespace.
  • .empty?: Returns true if the string is empty.
  • .gsub: Replaces all occurrences of one pattern with another.
  • .gsub!: Modify the original variable instead of creating a copy.

Example: Link to heading

"Hello world".gsub!("Hello", "Hi") # "Hi world"

Keep learning about data types and methods in Ruby to master this versatile language!

<< Object and symbol identifiers in Ruby >>