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(){
}
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
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
578 Understanding How to Configure Google API Key
582 PHP ssh2_scp_send fails to send files as intended
574 Who developed the "avformat-59.dll" that comes with FFmpeg?
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
918 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.