rubysubroutine

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.


Solution

  • 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")