Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

120
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

10 months 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

10 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos