Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a symbol from a string that has whitespaces?

Tags:

symbols

ruby

hash

I am creating a Ruby hash for movie names storage.

When the hash's keys are strings that contains whitespaces, it works just fine.

As in:

movies = {"Avatar" => 5, "Lord of the rings" => 4, "Godfather" => 4}

Now I am trying to replace the use of strings with symbols:

movies = {Avatar: 5, Lord of the rings: 4, Godfather: 4}

Obviously that doesn't work.

How does Ruby handle whitespaces in symbol naming?

like image 566
swapnesh Avatar asked Mar 12 '13 04:03

swapnesh


People also ask

How do you indicate a space in a string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') .

How do I check if a string has whitespace?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

How do you represent space as a character?

The character representation of a Space is simply ' ' .

Is space a character or string?

String variables contain strings of characters. The characters can be any printable character on the keyboard, including spaces and punctuation (but not function keys, the enter key, and some others.)


2 Answers

Try by yourself

"Lord of the rings".to_sym
#=> :"Lord of the rings"
like image 103
oldergod Avatar answered Nov 01 '22 18:11

oldergod


I'm not sure why you want to use symbols when you want spaces in the key values, but you can do that. You just can't do it using the <symbol>: <value> syntax...

{:Avatar => 5, :"Lord of the rings" => 4, :Godfather => 4}
like image 23
Steve Jorgensen Avatar answered Nov 01 '22 18:11

Steve Jorgensen