I am looking for a way to 'map' a single item in Ruby.
I want to call this function and pass it a block, the object will be yielded to the block, and then the result of the block will be returned to the caller. Exactly what map does, but for a single element.
The motivation is that sometimes you generate objects that are just used to construct something else. The original object is then no longer needed. It would be nice to just put the conversion into a block and eliminate the temporary.
As a contrived example, let's assume that I want to create an integer that represents the month/year combination. For today's date, the code would look something like:
day = Date.today
month_number = day.year * 100 + day.month
I'd really like it if I could do something like:
month_number = Date.today.some_function { |d| d.year * 100 + d.month }
But I don't know what 'some_function' is (or if it even exists).
If there is a more Ruby way of handling something like this, I'm all ears. I am aware of monkey patching classes, but I am looking to handle those cases that are a bit more transient.
The . map method will take an object and a block and will run the block for each element by outputting each of the values which are returned from the block. This will ensure that the original object will remain unchanged until the map is used.
Ruby Map with IndexesIf you want the resultant array to show up with indexes, you can simply do that by using with_index method. Let's see the code example. As you can see that with_index can be used with any data type. Using this method, the map will generate a resultant array featuring indexes.
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
The map() of enumerable is an inbuilt method in Ruby returns a new array with the results of running block once for every element in enum. The object is repeated every time for each enum. In case no object is given, it return nil for each enum.
instance_eval
is what you're looking for.
month_number = Date.today.instance_eval { |d| d.year * 100 + d.month }
The |d|
is also optional and self
defaults to the object context.
This may satisfy your needs in a more compact way.
month_number = Date.today.instance_eval { year * 100 + month }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With