.NET to Ruby: The Ruby Environment

Transitioning from .NET to Ruby:

Hi there! I hear you want to make the transition from .NET to Ruby. It’s not a hard task, but it’s always nice to start with guidance. I too was once in your shoes. Master of .NET, a LINQ superstar, CLR guru, Generics generalist, conqueror of WCP, WPF, and WF, and able to box with the best of them. And maybe you too are like I was; gazing over the fence into the Ruby pasture, wondering whether the grass is indeed greener? In keeping with the pasture metaphor, this series will be about shepherding you through the transition from .NET to Ruby [1]. In it we’ll dig deep into how the two languages stack up with one another. We’ll touch on some of the higher level items, like MVC frameworks, testing frameworks, and ORMs, but for this post we’ll start with the basics and figure out what Ruby is, and what tools you’ll need to be familiar with. Enough meta-post, let’s dive in.

What is Ruby?

The first order of business is to define what Ruby is. Ruby is a dynamic, strongly typed, and interpreted language. C# is a static, strongly typed language. Ruby was created in the mid-1990s by Yukihiro Matsumoto, Matz for short. First and foremost Ruby is Object Oriented, in fact it’s so object oriented that even its classes are objects, which as we’ll look at in this series, is one of the aspects that makes Ruby so powerful. The current version of Ruby is 1.9.2 and if you don’t have it installed you should! To get Ruby installed, and your environment properly setup, use Glenn Goodrich’s post Rails Development 101: RVM. This post assumes that you already have Ruby installed.

The Command Line

Ruby is run primarily from the command line. Unlike .NET, rubyists live on the command line, and with time you will come to love it! There are IDE’s out there, but you’ll find that most Ruby developers use emacs, vim, or textmate.

I highly recommend setting up a *nix[2] environment. Ruby will run on windows, but it is noticeably slower. The vast majority of developers do their work in *nix environments, so most of the resources you find online will have that bent, making it easier for you to make your Ruby transition from .NET.

Ruby programs are run using the command ruby. Using that, we can run a Ruby program right from the command line:

ruby -e 'puts "Hello World!"'

This command will output Hello World! to your console. The -e switch tells Ruby that it is executing a single line of script, and the single quotes around the code delimit the program.

We can also run programs by placing our code into a file with the .rb extension, and then passing that file name into the ruby command. Let’s try it. Inside a hello_world.rb file write the following:

# hello_world.rb
puts "Hello World!"

Then on the command line run the command:

ruby hello_world.rb

Because we’re using the command line so frequently, spaces can be a large source of trouble for Ruby, which is why we’ve named our file hello_world.rb instead of hello world.rb. As well, Ruby’s naming conventions keep most code lowercased instead of CamelCase like .NET – there are exceptions but we’ll leave naming conventions for another post.

IRB

Ruby also sports another nice tool for running code called the Interactive RuBy Shell (IRB) which you can launch from the command line like this:

irb

From within IRB you’re able to type in Ruby code, and see what happens when that code is executed. The nice thing about IRB is that you have the full power of Ruby, so you can define modules, classes, methods, and lamda functions just like a regular Ruby program. But be careful, once you close an IRB session all the code you’ve executed is lost, which is why it makes a better discovery tool, than permanent development environment.

So here’s an exercise to get you familiar with IRB. Run the following commands, and report back on what they output:

irb #=> To start irb 

arr = [1, 2, 3, 4] 
arr.first 
arr.include?(7) 
arr.include?(2) 
arr.join("-") 

exit #=> To exit irb

Hello World

Alright, so we’ve come full circle and we’re back at the Hello World programming example. It’s important to break down what’s going on here, because it’s different from .NET:

# hello_world.rb
puts "Hello World!" #=> Hello World!

The very first thing to notice is that Ruby doesn’t define a Main function like .NET does[3]. Instead Ruby starts at the top of your file and reads to the bottom. This parsing is done with a tool called Matz’s Ruby Interpreter – better known as MRI – which is a single pass parser. This is different from .NET which uses a multiple pass parser. What this means is that if we try to call a class or method that the interpreter hasn’t read yet we’ll get an error. When I made my switch from .NET to Ruby this was one of the issues I encountered regularly. When this happens you’ll be presented with an error that reads like this:

# This is a class error
uninitialized constant Object::Foo (NameError)

# This is a method error
undefined method `bar' for main:Object (NoMethodError)

Moving on, in the hello world program puts is a method used to write to console. At least that’s what the end result looks like. Behind the scenes what we’re really doing is calling puts on stdout. The code looks like this:

$stdout.puts("Hello World")

That’s a lot different from what we wrote, so let’s break it down. First a variable in Ruby that is prepended with a dollar sign refers to a global variable. In this case $stdout refers to the standard output stream.

stdout may be something you haven’t come up against in the .NET world, so let’s explain what it is. At its core, stdout is a connection between the program being run, and the context that executed it – in our case the context is a terminal, and our program is hello_world.rb. *nix systems start with 3 of these streams open when a program is run: stdin, stdout, and stderr. Input can be pulled off of stdin in Ruby using gets, we’ve already seen that puts writes to stdout, and if we had wanted to write to stderr we can access the stream using its global reference:

$stderr.puts("Error Message")

The other oddity in hello_world.rb is that we haven’t put brackets around the argument being passed to the puts method. That’s because the brackets are optional in Ruby. Which means you’re able to write the code below, and get the same result from both lines:

puts "Hello World!"
puts("Hello World!")

However odd this may seem, you’ll have to trust me that this is a fantastic feature of Ruby. I’m not going to tell you why right now, we’ve got some more ground to cover first, just stick this in the back of your mind for later.

And that there concludes your first foray into Ruby. Things might look at bit intimidating right now – we didn’t go through much code. But we’re laying the foundation that this series (and really any post on RubySource) will build upon. I hope you enjoyed it, and hope that you’ll come back for the next post where we’ll discuss Classes, Methods, Variables, and Blocks!

Finally, if there are any topics you’d like to see covered here, leave your idea in the comments and I’ll see what I can do.

Footnotes

[1] I’d hate for us to get off on the wrong foot. .NET != Ruby. .NET is a framework, and Ruby is not, Ruby is a language. For this series of posts we’ll really be comparing C# to Ruby. back

[2] For those of you coming from the Windows world you may have seen the term *nix used before, but may not have known what it means. *nix stands for any OS that behaves like Unix. back

[3] Main actually does exist. Because Ruby treats everything like an object, Main is actually defined within the top level object which your script runs in. If you want to test this write the following code into a file called test.rb and notice how “main” is the result that’s printed out:

# test.rb
puts self.to_s

back

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://blog.mmediasys.com Luis Lavena

    Hello, nice introduction, with one minor detail.

    “I highly recommend setting up a *nix[2] environment. Ruby will run on windows, but it is noticeably slower.”

    There is a small detail here: what is slow on Windows is not Ruby, but Rails.

    There is a flaw in Ruby that is mainly triggered when using Rails and not any other type of script or tasks users might end doing on Windows.

    In RAW computation, Ruby on Windows works pretty much at same speed than *nix counterparts.

    The penalty of performance is paid at startup of a Rails application and not at execution.

    While it can’t handle the same level of request than the *nix counterpart, it is still good performance to getting started.

    Regards.

    • http://www.thepursuitofquality.com Gavin Miller

      Thanks for clearing that up Luis!
      The majority of my Ruby on Windows experience was with Rails so my assumption was that it extended to the entire Ruby environment.

  • James Sumners

    You set yourself up as some sort of .NET expert and then you say:

    “In keeping with the pasture metaphor, this series will be about shepherding you through the transition from .NET to Ruby [1]. In it we’ll dig deep into how the two languages stack up with one another.”

    .NET is not a language. .NET is a framework. The comparison you likely want to make here is .NET to Ruby on Rails. Or maybe C#/VB.Net/IronPython/F#/etc. to Ruby?

    • http://www.thepursuitofquality.com Gavin Miller

      Hey James,

      You’re right, and the footnote to [1] says what you’ve just said:

      For this series of posts we’ll really be comparing C# to Ruby.

      • James Sumners

        I saw that _after_ I had stopped reading as a result of that problem. Footnotes in a web page don’t make any sense to me, so I skip them. Additionally, the content of the footnote is something that really should have been in the text. It is that important to your introduction. People like me are going to come along, read those first seven sentences, and then stop because of the glaring error.

  • saurabh

    Awesome post..cant wait for next round of series

  • gigi

    In the hope they don’t go unanswered just like the ones on ruby vs php, here are some more questions:

    1) What is the current estimated penetration of ruby at enterprise level?
    Is this figure expected to change anytime soon?
    2) What’s the level of integration of ruby with stuff like sql server reporting services?
    3) What’s the real advantage of moving towards ruby in an ms-centric world?
    4) If you were responsible for a 50 or more application-servers
    would you mess with IIS to let Mongrel run to let rails run?
    4-bis) In what ways rails is better than Asp.net mvc?
    5) What’s the current state of IronRuby?
    6) What happened to SAP BlueRuby?
    7) In what ways Vim or TextMate are better tools than VisualStudio?
    8) And finally, once again…would you explain why twitter migrated its engine
    from ruby to scala?

    Best Regards

    • http://www.thepursuitofquality.com Gavin Miller

      Hey Gigi – Lots of questions there. I’ll answer them as best as I can:

      1. Ruby is still in the early adopter phase when it comes to the enterprise. Mostly Ruby is popular with startups, which tend to be on the edge when it comes to technology adoption. With that said, some of the larger companies using Ruby/Rails are: Amazon, IBM, Oracle, NASA, and the poster child 37signals (ref.) I can’t give you a reliable answer on whether the number of businesses using Ruby is growing or not.

      2. Ruby integrates nicely with the common SQL databases. However there doesn’t seem to be much support for sql server reporting services.

      3. One of the big advantages for moving to Ruby in an MS world is rapid prototyping. You can get a lot done with a framework like Rails in minimal time. Other tools like Sinatra can allow you to mock out APIs very easily. The other advantage (and this is personal bias,) but I enjoy working with Ruby much more than .NET.

      4. I wouldn’t want to use IIS to run a ruby/rails app. As stated in a previous comment, rails doesn’t run well on windows, so I would run a setup on a linux box. As to which is better Rails or ASP.NET MVC, you’ll have to wait until we get to that part in the series! ;D

      5. I tried IronRuby about 6 months ago, and my evaluation was that it didn’t integrate nicely with Visual Studio. I didn’t pursue it much based on that first impression. From what I’ve heard MS has stopped funding IronRuby, so I wouldn’t bet money on whether it lives.

      6. I’m not familiar with SAP BlueRuby.

      7. I like using a Text Editor vs Visual Studio because I find myself more productive using it. The other thing I like is that I don’t get auto-complete, which may sound a bit Ludditish, but I find that I remember APIs better if auto-complete isn’t there. I use documentation more, and read it completely through so that I know what’s going on. In short, I feel like it makes me a better developer, because it encourages good practices.

      8. I can’t explain the twitter migration, but I can guess: Ruby no longer fit all their needs. A programming language is like a tool in a toolbox, some problems require hammers, others require screwdrivers. There’s no “one language to rule them all,” Twitter built itself on Ruby and outgrew it, just like a carpenter would outgrow a hammer and switch to a nail gun. Facebook did the same thing, they started out in PHP, and now they’ve adopted different technologies to fit their needs.

      I think your underlying question is: If Twitter outgrew Ruby why should I even bother? And the answer is evaluate your technical requirements and choose a language that best suits those needs. Don’t pick a language first.

      Hope that helps you out!

  • gigi

    Well first of all thanks for replying.
    Though I would like to argue a bit further :)
    1) Companies like Amazon, Oracle or IBM use a plethora of technologies but I highly doubt their focus and core technology is ruby.

    Points 2,4 and 5 confirm that even thinking of switching to ruby in some cases just wouldn’t make sense. Though I am genuinely interested in the mvc framework comparison.

    Points 3 and 7 are a bit to subjective (well at least they sound to me)

    Point 8 is a bit inaccurate as far as Facebook is concerned.
    The root cause was the same (poor performance of dynamic languages under extremely heavy load) but as a matter of fact the conclusion on the facebook’s developer blog was:
    “Overall HipHop allows us to keep the best aspects of PHP while taking advantage of the performance benefits of C++”

    which is somewhat different from what you can read here (http://www.artima.com/scalazine/articles/twitter_on_scala.html)

    And while I agree on your conclusion, I’d like to stress the fact that my problem is not that I’m working on the next twitter or that I’m a dumb ms fanboy developer but that in some ecosystems ruby and rails are simply not an option..(same goes for PHP)

    • http://www.thepursuitofquality.com Gavin Miller

      I think you’re spot on in what you’ve said. Ruby doesn’t fit every ecosystem. For example, I’m currently working on video encoding software. We’re doing it in C, C++, and some C# for UIs – there’s no chance we could do the C, C++ stuff in Ruby because we wouldn’t get the performance we needed. We could do the UI in Ruby, but sticking to C# fits our team’s knowledge base better.

      Overall I think that your response highlights the need to address the “Why switch from Ruby to .NET” question. As you say, there are good reasons, and bad reasons, and understanding those trade offs is what our employers pay us for! With that said, I’ll put it down on my list of potential future topics.

      And thanks for the sharp questions! I’m always up for a good debate/discussion, and it’s something that makes these posts even more valuable.

  • http://forloop.co.uk Russ Cam

    Cost is another comparison that could be made.

  • Sam Elliott

    I completed a major series of enhancements to a Ruby on Rails website last year using SapphireSteel Software’s implementation of Ruby called Ruby In Steel, which runs under Visual Studio. The environment was superb, with a very fast debugger identical in most respects to the sort of debugging experience I was used to with C# and VB.NET. I cannot recommend this product too highly to anyone wanting to develop in Ruby under Windows. Go to
    http://www.sapphiresteel.com/Blog/article/ruby-in-steel-2-launch
    for their recent new version supporting Ruby 1.9.2 within Visual Studio 2010. At $249 it is a steal…