How to Create Ruby Chain Method Functions

Asked 2 years ago, Updated 2 years ago, 48 views

Please tell me how to create a function that can use the chain method in ruby.

"string".hoge()

I want to make hoge

def hoge(){
}

ruby

2022-09-30 20:29

2 Answers

If you want to add a method to the class, do monkey patch.

class String
  def hoge
    # contents of a method
  end
end

"string".hoge

It is easy to make it a chain method.Make sure that the method returns self or objects of the same class.

class Foo
  defm1
    puts "hi"
    self
  end

  defm2
    puts "bye"
    self
  end
end

f = Foo.new.m2.m2
f.m1.m2.m2.m1

# output
# bye
# bye
# hi
# bye
# bye
# hi

It's not a chain method, but you can also try to pass blocks to allow for a compact writing during initialization.In this case, you can use the instance_eval method to get the block to run in the new object.

class Foo
  US>def initialize (&block)
    instance_eval (&block)
  end

  defm1
    puts "hi"
    self
  end

  defm2
    puts "bye"
    self
  end
end

f = Foo.new do
  m1()
  m2()
end

# output
# hi
# bye


2022-09-30 20:29

It's not a chain method, it's a chain method.This is the chain of methods.

The method chain is just a "syntax that allows a method call with the return value of the previous method as the receiver."

str="abc".trip#=>"abc"
str.upcase#=>"ABC"
# Put this together and put it like this.
" abc".stip.upcase#=>"ABC"
# If you add redundant parentheses, you're going to it's like this.
("abc".stip).upcase#=>"ABC"

It's about the caller, so you don't have to do anything special in the method definition (the caller).If you assume that another method is called in the method chain, simply return the object in the class that can receive the method as a return value.

The answer "I have to return self or an object of the same class" is incorrect.As mentioned above, it's just a method call syntax, so no matter what class of object you return, you can continue to write any method that the object can receive.

12345.to_s.length#=>5


2022-09-30 20:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.