How do I convert a Ruby string with brackets to an array?
You'll get what you want with YAML.
But there is a little problem with your string. YAML expects that there's a space behind the comma. So we need this
str = "[[this, is], [a, nested], [array]]"
Code:
require 'yaml'
str = "[[this, is],[a, nested],[array]]"
### transform your string in a valid YAML-String
str.gsub!(/(\,)(\S)/, "\\1 \\2")
YAML::load(str)
# => [["this", "is"], ["a", "nested"], ["array"]]
Ruby Array into string with brackets
I can't say how "ruby-ish" this is, but it's what I would typically do:
puts "['" + array_of_strings.join("','") + "']"
ruby 1.9 how to convert array to string without brackets
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.
How to convert a string to an array in Ruby
You can use json to convert it to an array.
class T
require 'json'
def array_detect(array_string)
begin
json = JSON.parse array_string
if json.is_a? Array
# is an array
else
# not an array
end
rescue JSON::ParserError => e
puts e.message
# not a valid json string
end
end
end
Removing the brackets from an array in Ruby
If you're storing your values as a string such as "123, 123"
then there is no point in map &:to_i
.
You can use plan_code.split(",").join(", ")
or alternatively plan_code.gsub(",", ", ")
Convert a string with brackets to tree, Ruby
Here is a one way you could convert the string to an array.
Code
def arrayify(arr)
a = split_arr(arr)
a.map do |h|
k = h.keys.first
v = h.values.first
case v
when Array then { k => arrayify(v) }
else { k=>v }
end
end
end
def split_arr(arr)
a = []
while arr.any?
word = arr.shift
if arr.empty? || arr.first != ?(
a << { word=>nil }
else
arr.shift
close_count = 0
b = []
loop do
token = arr.shift
case token
when ?)
break if close_count == 0
close_count -= 1
when ?( then close_count += 1
end
b << token
end
a << { word=>b }
end
end
a
end
Example
str = "Animals ( Reptiles Birds ( Eagles Pigeons Crows ) ) Foods ( " +
"Snacks Breakfast ( Pancakes Waffles ) )"
arrayify(str.split)
#=> [{"Animals"=>[{"Reptiles" =>nil},
# {"Birds" =>[{"Eagles" =>nil},
# {"Pigeons"=>nil},
# {"Crows" =>nil}
# ]
# }
# ]
# },
# {"Foods" =>[{"Snacks" =>nil},
# {"Breakfast"=>[{"Pancakes"=>nil},
# {"Waffles" =>nil}
# ]
# }
# ]
# }
# ]
Related Topics
Activerecord Connection Warning. (Database Connections Will Not Be Closed Automatically)
Unpermitted Parameters for Dynamic Forms in Rails 4
How to Render File in Rails 5 API
Encoding::Undefinedconversionerror: "\Xe4" from Ascii-8Bit to Utf-8
How to Decode a Cookie from the Header of a Websocket Connection Handshake? (Ruby)
Rvm and Osx Lion - Rvm 'Forgets' Gemsets on System Restart
Ruby - Calling Setters from Within an Object
Using Bsearch to Find Index for Inserting New Element into Sorted Array
How to Find If Range Is Contained in an Array of Ranges
Difference Between Lambda and -> Operator in Ruby
How to Setup a Local Ssl Certificate and a Rails Application