I have an array that looks like this:
nodes = ['server1','server1','server2']
In a chef recipe I need to convert into a set before I pass to a template erb. How do I do that?
The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.
The at() method of an array in Ruby is used to access elements of an array. It accepts an integer value and returns the element. This element is the one in which the index position is the value passed in.
To update an element in the array, assign a new value to the element's index by using the assignment operator, just like you would with a regular variable. To make sure you update the right element, you could use the index method to locate the element first, just like you did to find the element you wanted to delete.
Ruby | Set add() method The add is an inbuilt method in Ruby which adds an element to the set. It returns itself after addition. Parameters: The function takes the object to be added to the set. Return Value: It adds the object to the set and returns self.
if you want to make it unique (as a set is unique) but still as an array, you can use |[]
nodes = ['server1','server1','server2']
nodes|[]
# or nodes |= [] # for inplace operation
# => ["server1", "server2" ]
This pattern works with Set, Matrix, JSON etc.; it is the first thing to try.
require 'set'
nodes = ['server1','server1','server2']
p nodes.to_set # #<Set: {"server1", "server2"}>
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