How to convert string to hash WITHOUT EVAL [duplicate] - ruby-on-rails

This question already has answers here:
How do I convert a String object into a Hash object?
(16 answers)
Closed 8 years ago.
I have a string. {"response_code"=>"SUCCESS", "authorisation_result"=>"Approved", "transaction_number"=>"1234567", "receipt_number"=>"999999", :cents=>100} that is stored as a value in hstore in postgresql.
So it's a raw string not a YAML or a JSON.
I was wonering how to get the value back to the hash that was used to insert the record.
The idea of using EVAL scares the hell out of me, because there is potential for use input here.
This question might seem to be a replica of How to convert a string to a hash in ruby/rails without using eval?, but the answer there doesn't mesh with the question. It only offers eval as the solution. (I don't understand how the answer was marked as the answer)

Ruby hashes look pretty similar to JSON, so this would work for your example:
require 'json'
str = "{\"response_code\"=>\"SUCCESS\", \"authorisation_result\"=>\"Approved\", \"transaction_number\"=>\"1234567\", \"receipt_number\"=>\"999999\", :cents=>100}"
JSON.parse str.gsub(/:(\w+)/){"\"#{$1}\""}.gsub('=>', ':')
# => {"response_code"=>"SUCCESS", "authorisation_result"=>"Approved", "transaction_number"=>"1234567", "receipt_number"=>"999999", "cents"=>100}

Related

Ruby: <<- operator [duplicate]

This question already has answers here:
What are <-- Ruby Strings called? And how do I insert variables in them?
(3 answers)
Closed 6 years ago.
I'm working on Rails. In my code base, I see a line that using Arel::SqlLiteral like this:
result = Arel::Nodes::SqlLiteral.new(<<-SQL
CASE WHEN condition1 THEN calculation1
WHEN condition2 THEN calculation2
WHEN condition3 THEN calculation3
ELSE default_calculation END
SQL)
I understand what this code piece do. The thing I don't understand is its grammar, at this point:
Arel::Nodes::SqlLiteral.new(<<-SQL
...
SQL
)
So in ruby, what is the grammar of <<- follow by name, and then at last block we call that name.
thanks
The keyword you're looking for is "Heredoc".
https://ruby-doc.org/core-2.2.0/doc/syntax/literals_rdoc.html#label-Here+Documents
It's mainly used to prettify large texts and common practice for shells/shellscripts. The marker on top indicates the beginning of a heredoc and the marker on bottom (which must not be indented unless you place a “-” before the opening marker) specifies the end.

Extract array in string rails [duplicate]

This question already has answers here:
How do I convert this Ruby String into an Array?
(6 answers)
Closed 6 years ago.
My string is
"[1,2,3]"
I want to get output in the below format
[1,2,3]
I want to extract array present in my string.
Just parse it with JSON.parse method like this ;
JSON.parse("[1,2,3]")
You can use eval:
try:
eval("[1,2,3]")
=> [1, 2, 3]
Ok, try it:
"[1,2,3]".scan(/\w/).map{|x| x.to_i}

What does "&:name" mean in Ruby [duplicate]

This question already has answers here:
What does map(&:name) mean in Ruby?
(17 answers)
Closed 8 years ago.
I saw it in some sample Ruby code someone had posted. It was something like:
a.sort_by(&:name)
where a is an array or ActiveRecord objects and :name is one of the attributes.
I have never seen &:name and Ruby's Symbol class documentation says nothing about it. Probably something really simple. :)
Unary Ampersand is address of a function/block/lambda
In this case, it means that the .sort_by function will use each a's element's function named name for comparison
Mostly it used for something else, like this:
[1,2,3].map{ |x| x.to_s } # ['1','2','3']
That could be shortened as:
[1,2,3].map(&:to_s)
So, in your case, a.sort_by(&:name) is a shorthand to:
a.sort_by{ |x| x.name }

Erlang Tuple to String [duplicate]

This question already has answers here:
Convert erlang terms to string, or decode erlang binary
(2 answers)
Closed 9 years ago.
Is there a way how to convert a tuple to a string ?
Consider I have the following list :
[{atom,5,program},{atom,5,receiving},{nil,5}]
I wish to convert this into the following string:
"{atom,5,program},{atom,5,receiving},{nil,5}"
I have tried using erlang:tuple_to_list on each element in the list, which returns
A = [atom,5,program]
Eventually, I can't concatenate that with "{" ++ A ++ "}"
Any ideas how I can turn that to a string ?
Term = [{atom,5,program},{atom,5,receiving},{nil,5}].
lists:flatten(io_lib:format("~p", [Term])).

What does "temps.each(&:valid?)" mean in Ruby? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does map(&:name) mean in Ruby?
What does the &:valid? found in the each mean?
I've seen .each do |r| or whatever, but not sure how this one works?
The & is called the to_proc operator. It expands the symbol (:valid?) into a Proc.
So your example is equivalent to:
temps.each { |t| t.valid? }
&:symbol is a shorthand for symbol to proc.
Here's a good blog post on it.
http://blog.hasmanythrough.com/2006/3/7/symbol-to-proc-shorthand

Resources