1

I have created an array

steps = [{'title' =>'abc','content' =>'click this', 'target' => 'bca'}]
tours = ['id'=>'tour', 'steps:' => "#{steps}"]
puts tours 

Getting following output :

{"id"=>"tour", "steps:"=>"[{\"title\"=>\"abc\", \"content\"=>\"click this\", \"target\"=>\"bca\"}]"}

The structure of the output is right but i don't want these \ in the output. What should i do to remove these \. Thanks!

1
  • 1
    That's called escaping :) Commented Dec 14, 2015 at 10:56

2 Answers 2

2

In ruby "#{}" invoke the to_s method on the object. You can check it run the following code: steps.to_s.

Just use:

tours = ['id'=>'tour', 'steps:' => steps]

Because this:

"[{\"title\"=>\"abc\", \"content\"=>\"click this\", \"target\"=>\"bca\"}]"

is a string representation of:

[{'title' =>'abc','content' =>'click this', 'target' => 'bca'}]
Sign up to request clarification or add additional context in comments.

1 Comment

It's Rails way of outputting a legit string with escaped characters
0

Зелёный has the direct answer for you, however, there's a more pressing issue I would point out -- I think you're getting confused between {hashes} and [arrays]

--

An array is a set of unordered data:

array = [3, 4, 5, 6, 0, 5, 3, "cat", "dog"]

Arrays are mainly used for non-sequential collections of data, a good example being product_ids in a shopping cart.

Arrays can only be identified by using the location of the data inside the array:

array[1] # -> 4
array[2] # -> 5

--

A hash is a collection of key:value pairs:

hash = {name: "Greg", type: "cat"}

Hashes are used when you wish to assign multiple values to a single piece of data, and can be called by referencing the "key" of the hash:

hash["name"] #-> Greg
hash["type"] #-> cat

Whilst you can create an array of hashes:

 hash_array = [{name: "Greg", type: "cat"}, {name: "Sulla", type: "Dog"}]

... the problem with this is that you cannot call the hashes directly - they have to be through the array:

 hash_array["name"] # -> error
 hash_array[0]["name"] #-> "Greg"

Thus, I'd use the following in your example:

steps = {'title' =>'abc','content' =>'click this', 'target' => 'bca'}
tours = {id: 'tour', steps: steps}
tours.inspect #-> { id: "tour", steps: { "title" => "abc", "content" => "click this", "target" => "bca" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.