Movatterモバイル変換


[0]ホーム

URL:


Ruby

A Programmer's Best Friend

HomeDownloadsDocumentationLibrariesCommunityNewsSecurityAbout RubyMenu

To Ruby From C and C++

It’s difficult to write a bulleted list describing how your code will bedifferent in Ruby from C or C++ because it’s quite a large difference.One reason is that the Ruby runtime does so much for you. Ruby seemsabout as far as you can get from C’s “no hidden mechanism” principle—thewhole point of Ruby is to make the human’s job easier at the expense ofmaking the runtime shoulder more of the work. Unless or until youprofile your code for optimization, you don’t need to care one whitabout “keeping your compiler happy” when using Ruby.

That said, for one thing, you can expect your Ruby code to execute muchmore slowly than “equivalent” C or C++ code. At the same time, your headwill spin at how rapidly you can get a Ruby program up and running, aswell as at how few lines of code it will take to write it. Ruby is muchmuch simpler than C++—it will spoil you rotten.

Ruby is dynamically typed, rather than statically typed—the runtime doesas much as possible at run-time. For example, you don’t need to knowwhat modules your Ruby program will “link to” (that is, load and use) orwhat methods it will call ahead of time.

Happily, it turns out that Ruby and C have a healthy symbioticrelationship. Ruby supports so-called “extension modules”. These aremodules that you can use from your Ruby programs (and which, from theoutside, will look and act just like any other Ruby module), but whichare written in C. In this way, you can compartmentalize theperformance-critical parts of your Ruby software, and smelt those downto pure C.

And, of course, Ruby itself is written in C.

Similarities with C

As with C, in Ruby,…

  • You may program procedurally if you like (but it will still beobject-oriented behind the scenes).
  • Most of the operators are the same (including the compound assignmentand also bitwise operators). Though, Ruby doesn’t have++ or--.
  • You’ve got__FILE__ and__LINE__.
  • You can also have constants, though there’s no specialconstkeyword. Const-ness is enforced by a naming convention instead— namesstarting with a capital letter are for constants.
  • Strings go in double-quotes.
  • Strings are mutable.
  • Just like man pages, you can read most docs in your terminalwindow—though using theri command.
  • You’ve got the same sort of command-line debugger available.

Similarities with C++

As with C++, in Ruby,…

  • You’ve got mostly the same operators (even::).<< is often usedfor appending elements to a list. One note though: with Ruby you neveruse->—it’s always just..
  • public,private, andprotected do similar jobs.
  • Inheritance syntax is still only one character, but it’s< insteadof:.
  • You may put your code into “modules”, similar to hownamespace inC++ is used.
  • Exceptions work in a similar manner, though the keyword names havebeen changed to protect the innocent.

Differences from C

Unlike C, in Ruby,…

  • You don’t need to compile your code. You just run it directly.
  • Objects are strongly typed (and variable names themselves have no typeat all).
  • There’s no macros or preprocessor. No casts. No pointers (nor pointerarithmetic). No typedefs, sizeof, nor enums.
  • There are no header files. You just define your functions (usuallyreferred to as “methods”) and classes in the main source code files.
  • There’s no#define. Just use constants instead.
  • All variables live on the heap. Further, you don’t need to free themyourself—the garbage collector takes care of that.
  • Arguments to methods (i.e. functions) are passed by value, where thevalues are always object references.
  • It’srequire 'foo' instead of#include <foo> or#include "foo".
  • You cannot drop down to assembly.
  • There’s no semicolons ending lines.
  • You go without parentheses forif andwhile condition expressions.
  • Parentheses for method (i.e. function) calls are often optional.
  • You don’t usually use braces—just end multi-line constructs (likewhile loops) with anend keyword.
  • Thedo keyword is for so-called “blocks”. There’s no “do statement”like in C.
  • The term “block” means something different. It’s for a block of codethat you associate with a method call so the method body can call outto the block while it executes.
  • There are no variable declarations. You just assign to new nameson-the-fly when you need them.
  • When tested for truth, onlyfalse andnil evaluate to a falsevalue. Everything else is true (including0,0.0, and"0").
  • There is nochar—they are just 1-letter strings.
  • Strings don’t end with a null byte.
  • Array literals go in brackets instead of braces.
  • Arrays just automatically get bigger when you stuff more elements intothem.
  • If you add two arrays, you get back a new and bigger array (of course,allocated on the heap) instead of doing pointer arithmetic.
  • More often than not, everything is an expression (that is, things likewhile statements actually evaluate to an rvalue).

Differences from C++

Unlike C++, in Ruby,…

  • There’s no explicit references. That is, in Ruby, every variable isjust an automatically dereferenced name for some object.
  • Objects are strongly butdynamically typed. The runtime discoversat runtime if that method call actually works.
  • The “constructor” is calledinitialize instead of the class name.
  • All methods are always virtual.
  • “Class” (static) variable names always begin with@@ (as in@@total_widgets).
  • You don’t directly access member variables—all access to public membervariables (known in Ruby as attributes) is via methods.
  • It’sself instead ofthis.
  • Some methods end in a ’?’ or a ’!’. It’s actually part of the methodname.
  • There’s no multiple inheritance per se. Though Ruby has “mixins” (i.e.you can “inherit” all instance methods of a module).
  • There are some enforced case-conventions (ex. class names start with acapital letter, variables start with a lowercase letter).
  • Parentheses for method calls are usually optional.
  • You can re-open a class anytime and add more methods.
  • There’s no need of C++ templates (since you can assign any kind ofobject to a given variable, and types get figured out at runtimeanyway). No casting either.
  • Iteration is done a bit differently. In Ruby, you don’t use a separateiterator object (likevector<T>::const_iterator iter).Instead you use an iterator method of the container object (likeeach)that takes a block of code to which it passes successive elements.
  • There’s only two container types:Array andHash.
  • There’s no type conversions. With Ruby though, you’ll probably findthat they aren’t necessary.
  • Multithreading is built-in, but as of Ruby 1.8 they are “greenthreads” (implemented only within the interpreter) as opposed tonative threads.
  • A unit testing lib comes standard with Ruby.

Participate in a friendly and growing community.

Syndicate

Recent News (RSS)


HomeDownloadsDocumentationLibrariesCommunityNewsSecurityAbout Ruby

This site in other languages:Български,Deutsch,English,Español,Français,Bahasa Indonesia,Italiano,日本語,한국어,polski,Português,Русский,Türkçe,Tiếng Việt,简体中文,繁體中文.

This website is proudly maintained by members of the Ruby community.


[8]ページ先頭

©2009-2025 Movatter.jp