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

240
Vistas
How to store a subroutine to a variable in Ruby?

I am trying to prove that you can store subroutines inside a variable (unless you can't). Any chance that I just have this code all wrong?

I have this code from Python that does what I want to do

def printSample(str)   
   puts str 
end  
x = printSample 
str = "Hello" 
x(str) 

expected output:

Hello

I am a beginner in Ruby and just trying to learn basic codes.

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

0

Your Python code can be translated to Ruby as:

def print_sample(str)
  puts str
end

x = method(:print_sample)
str = "Hello"
x.(str)

The main difference is that because parentheses in Ruby are optional, writing x = print_sample would already invoke the method. Retrieving a Method object that you can call later is a little more involved: you have to call method and pass the method name as a symbol or string. (the receiver being the object the method is defined in)

And because method objects are regular objects, the syntax for actually calling the method is also slightly different. Ruby provides:

x[str]
x.(str)
x.call(str)

With x.(str) being syntactic sugar for x.call(str), see Method#call


Another approach is to just store the method name and to invoke the method dynamically via send / public_send, e.g.:

x = :print_sample
str = "Hello"
send(x, str)

Referring to methods via their (symbolized) name is quite idiomatic in Ruby.

over 4 years ago · Santiago Trujillo Denunciar

0

Example for handling an instance method:

class Demo
  def initialize(s); @s = s; end
  def printSample(str); puts(@s+str); end
end

x = Demo.instance_method(:printSample)
# x is now of class UnboundMethod

aDemo = Demo.new("Hi")

# Use x
x.bind(aDemo).call("You")  # Outputs: HiYou

In this example, we first stored the method, and then applied it to an instance. If you have the instance first and want to fetch the method later, it is even simpler. Assuming the class definition of Demo from above, you can equally well do a

aDemo = Demo.new("Hi")
y = aDemo.method(:printSample)
y.call("You")
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