Learning Ruby: Syntax (Part 3)

Methods

>>> x = [10, 20, 30]
>>> a, *b = x
>>> print(f'{a=}, {b=}')
a=10, b=[20, 30]

Python ☝️, Ruby 👇

>> first, *rest, last  = ["a", "b", "c", "d"]
=> ["a", "b", "c", "d"]
>> first
=> "a"
>> rest
=> ["b", "c"]
>> last
=> "d"
>>

But in Ruby, splat operator can also create an array.

>> q=*135
=> [135]
>> q
=> [135]

In the second scenario1, it creates an array. I think this is useful for scenario where the method accepts either a single element or an array.

In python, we have to write an awkward code like


if isinstance(item, int):
  my_list = [item]

classes

# Derived class
class Derived < Baseclass
end
module ModuleExample
  def foo
    'foo'
  end
end

# Including modules binds their methods to the class instances.
# Extending modules binds their methods to the class itself.
class Person
  include ModuleExample
end

class Book
  extend ModuleExample
end

Person.foo     #=> NoMethodError: undefined method `foo' for Person:Class
Person.new.foo #=> "foo"
Book.foo       #=> "foo"
Book.new.foo   #=> NoMethodError: undefined method `foo'
irb(main):015:0> Var = "I'm a constant"
=> "I'm a constant"
irb(main):016:0> Var.upcase!
=> "I'M A CONSTANT"
irb(main):017:0> Var
=> "I'M A CONSTANT"
irb(main):018:0> defined? Var
=> "constant"
irb(main):022:0> Var = "I can change"
(irb):22: warning: already initialized constant Var
(irb):19: warning: previous definition of Var was here
irb(main):001:0> Var = "I can change"
=> "I can change"
irb(main):002:0> Var.freeze
=> "I can change"
irb(main):003:0>  Var.upcase!
(irb):3:in `upcase!': can't modify frozen String: "I can change" (FrozenError)
...
...
...
irb(main):004:0> Var
=> "I can change"

Last Updated: Jan 22, 2022. Added details of how splat operator can also construct an array


  1. I came across this second use here ↩︎