The last few weeks, I’ve been having to work in Ruby 2.x. It’s not a language that I’ve spent a great deal of time with, so it’s been fun to dive into the nuances of the platform. There’s a lot of things to like about it, including some simple syntaxes for common tasks in other languages. It can make it a powerful tool for some complex jobs. As someone that programs in multiple different languages, I often see many aspects that are similar, as well as certain aspects that make the language more powerful by requiring less code.
For the benefit of others that might be trying to learn either language, I’ll show a few pieces of code in both Ruby and C# (which is similar to Java and JavaScript). There’s obviously lots of ways to do the same tasks, but hopefully this helps you to at least draw some parallels.
Ruby | C# | Comment |
---|---|---|
|
| Ruby has a simple syntax for string arrays. |
|
| Ruby allows named parameters and they can be provided in any order if they are named (end with : ). C# expects a specific order and type. Ruby allows explicit return values (like C#), but also supports implicit (returning the value from the last evaluated statement). |
|
| Lambda expressions and string interpolation can be very similar in both languages |
|
| Configuring a Dictionary (C#) or Hash (Ruby) isn’t tough, but it’s definitely more elegant in Ruby! |
|
| Ternary operators. It’s nice when they just work. ❤️ |
|
| A simple for-each loop |
|
| Iterate each item in items , returning the .value property and creating an iterable entity. |
|
| With C#, you want to use a List<T> to work with mutable lists of values. With .NET, you tend to prefer to work with enumerable collections as opposed to using ToArray to return to an array. To work with an Array natively, you need to resize the array in order to add a value. Ruby hides the technical aspects of reallocating arrays. C# can do this as well … if you stick to using Collections. |
|
| Finding the first member of a collection that matches a criteria is very similar, esp. if you’re using C#’s Language-Integrated Query ( LINQ) |