Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!