Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby 3.1.2 how to reference an object property as a method parameter

This may be trivial. I want to reference an object property from within an object method parameter list, if that makes sense.

Trivial example:

'tags'.ljust([calculated_length, obj.length].max)

where, in this example, obj refers to the string tags.

Is this even possible?

like image 1000
willyab Avatar asked Dec 21 '25 06:12

willyab


1 Answers

reference an object property from within an object method parameter list

Although you are within the method's arguments, you're still outside the object's scope. Ruby doesn't provide a reference to the object at that point.

If you want to refer to the same object multiple times, you'd usually just assign it to a variable:

str = 'tags'
str.ljust([8, str.length].max)
#=> "tags    "

If you don't want to do that, there's yield_self which yields the receiver to the given block and returns the block's result:

'tags'.yield_self { |str| str.ljust([8, str.length].max) }
#=> "tags    "

You can shorten this a little by referring to the block argument via _1:

'tags'.yield_self { _1.ljust([8, _1.length].max) }
#=> "tags    "
like image 83
Stefan Avatar answered Dec 23 '25 21:12

Stefan



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!