Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ruby, how do I convert all array values to a given type?

Tags:

arrays

ruby

I need to convert fixnums to strings. My solution is:

arr.map {|a| a.to_s}

Is there a better way?

like image 524
herpderp Avatar asked Nov 30 '10 23:11

herpderp


People also ask

How do I convert an array to a string in Ruby?

In Ruby, we can convert an array into a string using the join method. The join method takes the array and a separator as the arguments. It then separates the elements in the array using the specified separator value.

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.

How do you print an entire array in Ruby?

The array as a parameter to the puts or print method is the simplest way to print the contents of the array. Each element is printed on a separate line. Using the inspect method, the output is more readable. The line prints the string representation of the array to the terminal.

How do you typecast in Ruby?

The user can convert strings to ints or floats by using the methods to_i and to_f , respectively. Other types to string: The user can convert other datatypes to string by using the to_s method.


1 Answers

arr.map(&:to_s)

This uses a spiffy new feature in Ruby >= 1.8.7, the "symbol to proc" shortcut, and is equivalent to the code in your question.

like image 195
Wayne Conrad Avatar answered Oct 13 '22 19:10

Wayne Conrad