RubyLearning

Helping Ruby Programmers become Awesome!

Ruby Features

Ruby has many features that make it a powerful and enjoyable language to use. Here are some of the key features:

Everything is an Object

In Ruby, everything is an object. This includes numbers, strings, and even classes themselves. This consistent object-oriented approach makes Ruby very intuitive.


# Numbers are objects
5.times { puts "Hello" }

# Strings are objects
"hello".upcase  # => "HELLO"

# Even nil is an object
nil.class  # => NilClass
      

Dynamic Typing

Ruby is dynamically typed, meaning you don't need to declare variable types. Variables can hold any type of object and can change types during execution.


x = 5        # x is an Integer
x = "hello"  # now x is a String
x = [1,2,3]  # now x is an Array
      

Blocks and Iterators

Ruby's blocks are chunks of code that you can pass to methods. Combined with iterators, they provide a powerful and elegant way to work with collections.


# Using a block with each
[1, 2, 3].each do |num|
  puts num * 2
end

# Using a block with map
squares = [1, 2, 3].map { |n| n ** 2 }
# => [1, 4, 9]
      

Mixins

Ruby uses mixins instead of multiple inheritance. Modules can be "mixed in" to classes to share functionality.


module Greetable
  def greet
    "Hello, I'm #{name}"
  end
end

class Person
  include Greetable
  attr_accessor :name
end
      

Open Classes

Ruby classes are open, meaning you can modify them even after they're defined. This allows you to add methods to existing classes, including built-in ones.


class String
  def shout
    self.upcase + "!"
  end
end

"hello".shout  # => "HELLO!"
      

Note: While open classes are powerful, use them carefully. Modifying core classes can lead to unexpected behavior if not done thoughtfully.