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?
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(' ') .
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.
The character representation of a Space is simply ' ' .
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.)
Try by yourself
"Lord of the rings".to_sym
#=> :"Lord of the rings"
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With