String concatenation in Ruby

December 02, 2010

  • Rails
  • Ruby
  • ruby-on-rails
  • strings
  • string
  • concatenation

One of colleagues Dhaval Jain explained me the different ways in which we can perform string concatenation in Ruby. I learnt from him some ways that I didn’t know earlier than today. So I thought it would be great to share it with everyone who are in the similar position that I was before this encounter. So let’s begin.

  1. Using the plus(‘+’) sign

This is the one basic way which I think everyone knows. But anyways here is an example.

irb(main):001:0> fname = "Rohit "
=> "Rohit "
irb(main):002:0> lname = "Sharma"
=> "Sharma"
irb(main):003:0> name = fname + lname
=> "Rohit Sharma"
  1. Using the << symbol

This is another way which helps in string concatenation. When Dhaval asked me what are the different ways of string concatenation in Ruby, I actually guessed this one and I had no knowledge of this prior to today. Here is an example :

irb(main):001:0> fname = "Rohit "
=> "Rohit "
irb(main):002:0> lname = "Sharma"
=> "Sharma"
irb(main):003:0> name = fname << lname
=> "Rohit Sharma"
  1. Passing the two string objects as parameter to the third

This is the one which surprised me, and lead me into writing this post. Here is an example.

irb(main):001:0> name = "Rohit " "Sharma"
=> "Rohit Sharma"

This definitely works, but there is an issue in this, which we are not able to figure out. The issue is, if we store two strings in two different variables and then try to concatenate them using this mechanism, then it doesn’t work. Here’s what we tried and got an undefined method error

irb(main):001:0> fname = "Rohit "
=> "Rohit "
irb(main):002:0> lname = "Sharma"
=> "Sharma"
irb(main):003:0> name = fname lname
NoMethodError: undefined method `fname' for main:Object
        from (irb):3

The reason that this doesn’t work is because, the error is related to the fact that fname would have to be a function for this to work. Ruby will consider fname as a method and lname as the parameter to the method. And that’s the main reason for this error. Because we have no method with the name fname. So it results in a NoMethodError. We can do this instead,

irb(main):001:0> fname = "Rohit "
=> "Rohit "
irb(main):002:0> lname = "Sharma"
=> "Sharma"
irb(main):003:0> name = "#{fname}#{lname}"
=> "Rohit Sharma"

Have a great day :)


LOCATION

Mumbai, Maharashtra, India

AROUND THE WEB

Copyright © 2021