C# to Ruby String Interpolation

July 20, 2014

Why?

Working with strings is part and parcel of any programming language. In C#, we use String.Format to do a lot of interpolation and manipulation. Here is a simple example using C#

using System;

namespace Foo 
{
	public class Program 
	{
		public void Main(string[] args)
		{
			var name = "Deon Heyns";
			var reallyLike = "Programming";
			var sentence = string.Format("Hello my name is {0} and I love {1}", name, reallyLike);
			Console.WriteLine(sentence);

			var result = Factorial(3) * 7;
			var answer = string.Format("The answer is {0}, which is also the answer to everything", result);
			Console.WriteLine(answer)

		}

		public static int Factorial(int n) 
		{
			return n == 0 ? 1 : n * Factorial(n - 1);
		}
	} 
}

How?

Now how do we accomplish the same thing in Ruby?

name = "Deon Heyns"
reallyLike = "Programming"
sentence = "Hello my name is #{name} and I love #{reallyLike}"
puts sentence

result = "The answer is #{ def factorial(n)
							n == 0 ? 1 : n*factorial(n-1)
						   end
						   factorial(3)*7 }, which is also the answer to everything"

puts results

From this code you see we are not using a position within our string to specify what variable goes where, we do this explicitly +1. You can define a method, in the middle of this string! What you might see here is that you need to use double quotes (“) and you use the hash / pound / number sign with curly braces to define a variable. There isn’t too much else to mention here. It’s pretty straight-forward and to me it seems like a better way to add your variables within the string since you don’t need to worry about positioning.

Conclusion

Ruby strikes again! Again I see that Ruby wants you to use fewer key strokes and be more explicit about what you want to do. What an awesome language!


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus