Sometimes I need a similar function in the standard library. This name can be, for example, with or with_it
(Repeating the previous code with a new name)
class Object def with_it(&block) block.call(self) end end
Usage example:
x = [1, 2, 3, 4, 5].map {|x| x * x }.with_it do |list| head = list.unshift list << head * 10 list.join " / " end
Unlike:
list = [1, 2, 3, 4, 5].map {|x| x * x } head = list.unshift list << head * 10 x = list.join " / "
While the latter is easier to understand, the former has the advantage of keeping the list and head variables in scope and the x assignment is clearer in my opinion (the assignment x should be inserted in the last line of code). Priority would be useful if the code was part of a larger method.
Another use with_it would therefore be to put the code in a separate method. For instance:
def mult_head_and_join(list) head = list.unshift list << head * 10 list.join " / " end x = mult_head_and_join [1, 2, 3, 4, 5].map {|x| x * x }
Not sure what to conclude here, but I think I would vote for with_it to be included in the standard library
source share