arraysrubystringexceptionnameerror

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?


Solution

  • 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    "