Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain method calls in Ruby

Tags:

ruby

Is there an elegant way to "continue if success" in Ruby? Something like this:

method1(a, b)
 .and_then(method2)
 .and_then(method3)
 .fail { |x| 'something is wrong'}
like image 352
Incerteza Avatar asked Dec 30 '25 13:12

Incerteza


2 Answers

I don't believe there is a way to do it exactly how you have shown, however you could use a begin and rescue block instead.

So the code would look like this:

begin
    method1(a,b).method2.method3
rescue
    p "something is wrong"
end

In any of the three methods, you should raise some sort of exception, simply by calling

raise "Something is Wrong"

and this will stop execution and run the rescue block. If you want to get some sort of data from the execution context where the raise call happened, you will need to implement your own type of error or use the existing types. If you wish to do this the rescue statement would need to be changed as follows

rescue => e

or if you have a type

rescue ArgumentError => e

This is a bit complex so at good article can be found here

This will only work if the methods you call actually raise exceptions.

like image 70
Zara Kay Avatar answered Jan 01 '26 06:01

Zara Kay


Using tap you can “tap into” a method chain, in order to perform operations on intermediate results within the chain. Inside the tap block you can place your conditions.

 method1(a, b).tap{|o| o.method2 if cond1}.tap{|o|o.method3 if cond2}
like image 25
shivam Avatar answered Jan 01 '26 07:01

shivam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!