Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chef and ruby: how to convert a array into a set

Tags:

ruby

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?

like image 897
Tampa Avatar asked Mar 26 '13 23:03

Tampa


People also ask

How do you turn an array into a hash in Ruby?

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.

How do you access the elements of an array in Ruby?

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.

How do you update an array in Ruby?

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.

How do I add an element to a set in Ruby?

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.


Video Answer


2 Answers

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" ]
like image 187
Kokizzu Avatar answered Sep 22 '22 07:09

Kokizzu


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"}>
like image 31
steenslag Avatar answered Sep 22 '22 07:09

steenslag