My question is about how to convert array elements to string in ruby 1.9 without getting the brackets and quotation marks. I've got an array (DB extract), from which I want to use to create a periodic report.
myArray = ["Apple", "Pear", "Banana", "2", "15", "12"]
In ruby 1.8 I had the following line
reportStr = "In the first quarter we sold " + myArray[3].to_s + " " + myArray[0].to_s + "(s)."
puts reportStr
Which produced the (wanted) output
In the first quarter we sold 2 Apple(s).
The same two lines in ruby 1.9 produce (not wanted)
In the first quarter we sold ["2"] ["Apple"] (s).
After reading in the documentation Ruby 1.9.3 doc#Array#slice I thought I could produce code like
reportStr = "In the first quarter we sold " + myArray[3] + " " + myArray[0] + "(s)."
puts reportStr
which returns a runtime error
/home/test/example.rb:450:in `+': can't convert Array into String (TypeError)
My current solution is to remove brackets and quotation marks with a temporary string, like
tempStr0 = myArray[0].to_s
myLength = tempStr0.length
tempStr0 = tempStr0[2..myLength-3]
tempStr3 = myArray[3].to_s
myLength = tempStr3.length
tempStr3 = tempStr3[2..myLength-3]
reportStr = "In the first quarter we sold " + tempStr3 + " " + tempStr0 + "(s)."
puts reportStr
which in general works.
However, what would be a more elegant "ruby" way how to do that?
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.
Ruby printing array contents 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.
The command is Array. delete_at(Array. index(value)) will remove the first occurance of a repeating value from the array.
An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects. This can condense and organize your code, making it more readable and maintainable.
You can use the .join
method.
For example:
my_array = ["Apple", "Pear", "Banana"]
my_array.join(', ') # returns string separating array elements with arg to `join`
=> Apple, Pear, Banana
Use interpolation instead of concatenation:
reportStr = "In the first quarter we sold #{myArray[3]} #{myArray[0]}(s)."
It's more idiomatic, more efficient, requires less typing and automatically calls to_s
for you.
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