Code block which allows dynamical numbers of arguments

Hi,
let’s pretend I have a codeblock like this:

#begin
test = lambda {|c,d| @check = c if object.status == d}
test.call(“GoodBoy”,12)
#end

So you see if object.status is 12 @check will be set to “Goodboy”.

But how can I make the block test to allow more than 2 arguments and
that any further argument will be takes as further conditional
statement?

Like:

test = lambda {|c,d,e| @check = c if object.status == d or object.status
== e}
test.call(“GoodBoy”,24,11)

or with 4 arguments:

test = lambda {|c,d,e,f| @check = c if object.status == d or
object.status == e or object.status == f}
test.call(“GoodBoy”,82,31,40)

so you see what I mean?

This should just happen automatically so I wanna call test sometimes
with 2, but sometimes also with more arguments and it shall be extended
as shown above.

Is there any way in ruby to do so?


greets
(
)
(
/\ .-"""-. /
//\/ , //\
|/| ,;;;;;, |/|
//\;-"""-;///\
// / . / \
(| ,-| \ | / |-, |)
//__\.-.-./__\
// /.-(() ())-.\ \
(\ |) ‘—’ (| /)
(| |)
jgs ) (/

one must still have chaos in oneself to be able to give birth to a
dancing star

On 4/28/07, anansi [email protected] wrote:

that any further argument will be takes as further conditional statement?

Is there any way in ruby to do so?

test = lambda {|c,d| @check = c if 12 == d}=>
#Proc:[email protected]:14(irb)
test.call(“GoodBoy”,11)
=> nil
test.call(“GoodBoy”,12)
=> “GoodBoy”

test = lambda {|*args| @check = args[0] if 12 == args[1]}
=> #Proc:[email protected]:21(irb)
test.call(“GoodBoy”,11)
=> nil
test.call(“GoodBoy”,12)
=> “GoodBoy”

test = lambda {|*args| @check = args[0] if args[1…-1].include? 12}
=> #Proc:[email protected]:28(irb)
test.call(“GoodBoy”,11)
=> nil
test.call(“GoodBoy”,11,13)
=> nil
test.call(“GoodBoy”,11,13,12)
=> “GoodBoy”

You’d want to use the excellent splat (*) operator for that.

lambda { |check, *statuses| @check = check if statuses.include?
(object.status) }

To get an idea of what happens, see the following:

irb(main):011:0> test = lambda { |c, *args| puts c.inspect; puts
args.inspect }
=> #Proc:[email protected]:11(irb)
irb(main):012:0> test.call(‘test’)
“test”
[]
=> nil
irb(main):013:0> test.call(‘test’, 1)
“test”
[1]
=> nil
irb(main):014:0> test.call(‘test’, 1,2,3,4)
“test”
[1, 2, 3, 4]
=> nil

thank you both :smiley: worked like a charm


greets
(
)
(
/\ .-"""-. /
//\/ , //\
|/| ,;;;;;, |/|
//\;-"""-;///\
// / . / \
(| ,-| \ | / |-, |)
//__\.-.-./__\
// /.-(() ())-.\ \
(\ |) ‘—’ (| /)
(| |)
jgs ) (/

one must still have chaos in oneself to be able to give birth to a
dancing star

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs