Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda