A little problem

Hi
What is difference between these 2 codes ?
(when I executed these codes result was the same )

···

---------------------
def welcome1( name )
puts "Hello#{name}"
end

def welcome2( name )
puts "Hello"+name
end

welcome1( Amir )
welcome2( Amir )

---------------------
--
Posted via http://www.ruby-forum.com/.

In the first function, you're performing interpolation on the variable;
i.e. the #{} construct, when included inside "", indicates to the
interpreter to evaluate it as code, not text.

In the second function, you're performing concatenation of the string
"Hello" with the value of the variable name. In this case, the
interpolation is automatic since the variable is outside the "".

Hope this helps.

···

On Wed, 2010-08-04 at 14:57 -0500, Amir Ebrahimifard wrote:

Hi
What is difference between these 2 codes ?
(when I executed these codes result was the same )

---------------------
def welcome1( name )
puts "Hello#{name}"
end

def welcome2( name )
puts "Hello"+name
end

welcome1( Amir )
welcome2( Amir )

---------------------

Try this:

welcome1(3)
welcome2(3)

You'll see the difference. It's because a string interpolation as in
your first example implicitly calls #to_s on it's result.

Vale,
Marvin

···

Am 04.08.2010 21:57, schrieb Amir Ebrahimifard:

Hi
What is difference between these 2 codes ?
(when I executed these codes result was the same )

---------------------
def welcome1( name )
puts "Hello#{name}"
end

def welcome2( name )
puts "Hello"+name
end

welcome1( Amir )
welcome2( Amir )

---------------------

Amir Ebrahimifard wrote:

Hi
What is difference between these 2 codes ?
(when I executed these codes result was the same )

---------------------
def welcome1( name )
puts "Hello#{name}"
end

def welcome2( name )
puts "Hello"+name
end

welcome1( Amir )
welcome2( Amir )

---------------------

The first calls #to_s and the second calls #to_str. The #to_str method is usually only defined for objects that are already String-like. The #to_s is usually defined for everything.

def welcome1( name )
  puts "Hello#{name}"
end

def welcome2( name )
  puts "Hello"+name
end

Amir = Object.new

def Amir.to_s
   puts "to_s"
   "Amir"
end

def Amir.to_str
   puts "to_str"
   "Amir"
end

welcome1( Amir )
welcome2( Amir )