Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you replace a string with a hash collection value in Ruby?

Tags:

ruby

I have a hash collection: my_hash = {"1" => "apple", "2" => "bee", "3" => "cat"}

What syntax would I use to replace the first occurrence of the key with hash collection value in a string?

eg my input string: str = I want a 3

The resulting string would be: str = I want a cat

like image 875
Goalie Avatar asked Apr 09 '12 22:04

Goalie


People also ask

How do you replace a string in Ruby?

Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string.

How do I change the value of a Hash in Ruby?

Modifying hashes in Ruby: Hash can be modified by adding or deleting a key value/pair in an already existing hash. Also, you can change the existing value of key in the hash.

How does Ruby store data in Hash?

Ruby | Hash store() methodHash#store() is a Hash class method that returns an add-on value with the key given by the key-value argument. Return: add on value with the key given by the key-value argument.

How do you write Hash in Ruby?

Most commonly, a hash is created using symbols as keys and any data types as values. All key-value pairs in a hash are surrounded by curly braces {} and comma separated. Hashes can be created with two syntaxes. The older syntax comes with a => sign to separate the key and the value.


2 Answers

My one liner:

hash.each { |k, v| str[k] &&= v }

or using String#sub! method:

hash.each { |k, v| str.sub!(k, v) }
like image 136
Hauleth Avatar answered Oct 12 '22 11:10

Hauleth


"I want a %{b}" % {c: "apple", b: "bee", a: "cat"}
=> "I want a bee"
like image 44
Matthias Winkelmann Avatar answered Oct 12 '22 12:10

Matthias Winkelmann