Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symbol to string issue

Following code fails

world = :world result = 'hello' + world puts result #=> can't convert Symbol into String 

Following code works

world = :world result = "hello #{world}" puts result #=> hello world 

Why?

Using ruby 1.8.7

like image 604
Nick Vanderbilt Avatar asked Dec 06 '10 02:12

Nick Vanderbilt


People also ask

What is the symbol of a string?

A string (or word) over Σ is any finite sequence of symbols from Σ. For example, if Σ = {0, 1}, then 01011 is a string over Σ. The length of a string s is the number of symbols in s (the length of the sequence) and can be any non-negative integer; it is often denoted as |s|.

How do I convert a symbol to a string in Ruby?

Converting between symbols to strings is easy - use the . to_s method. Converting string to symbols is equally easy - use the . to_sym method.

What is difference between string and symbol in rails?

A string, in Ruby, is a mutable series of characters or bytes. Symbols, on the other hand, are immutable values. Just like the integer 2 is a value. Mutability is the ability for an object to change.

What is to string in JavaScript?

The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string. Normally, you will not use it in your own code.


1 Answers

String interpolation is an implicit to_s call. So, something like this:

result = "hello #{expr}" 

is more or less equivalent to this:

result = "hello " + expr.to_s 

As karim79 said, a symbol is not a string but symbols do have to_s methods so your interpolation works; your attempt at using + for concatenation doesn't work because there is no implementation of + available that understand a string on the left side and a symbol on the right.

like image 82
mu is too short Avatar answered Nov 10 '22 16:11

mu is too short