Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

463
Vistas
How do I call a ruby function named []?

I am new to Ruby, so please excuse this question if it is obvious.

I am working with a Module with a function signature that I don't understand. How would I call this function?

module Facter
...
  def self.[](name)
    collection.fact(name)
  end
...

In my code I want to reference something that should be in collection.fact, in this Facter module. What syntax to I use to call this function?

Cheers

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

It works like this:

class MyModule
  def self.[](arg)
    puts arg
  end
end

MyModule["Hello world"] # will print Hello world

Please see official docs:

https://ruby-doc.org/core/doc/syntax/methods_rdoc.html

Additionally, methods for element reference and assignment may be defined: [] and []= respectively. Both can take one or more arguments, and element reference can take none.

class C
  def [](a, b)
    puts a + b
  end

  def []=(a, b, c)
    puts a * b + c
  end
end

obj = C.new

obj[2, 3]     # prints "5"
obj[2, 3] = 4 # prints "10"

So about example from docs

# From docs
obj[2, 3]

# It's the same as
obj.[](2, 3)

More interesting example

# From docs
obj[2, 3] = 4
# will print 10
# => 4

# It's the almost as
obj.[]=(2, 3, 4)
# will print 10
# => nil

As you see when you call as obj[2, 3] = 4 Ruby takes the value after = as the last argument of the []= method and return it as method result

And regardless of whether there is return in the method body. For example

class C
  def []=(a, b, c)
    puts "Before return"
    return 12
    puts "After return"
  end
end

obj = C.new

obj[2, 3] = 4
# will print Before return
# => 4

obj.[]=(2, 3, 4)
# will print Before return
# => 12

It is desirable to define such method with more than one parameter. Technically, you can have only one, but the call will be like this obj[] = 1

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda