Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Ruby Comes to the .NET Platform : Page 2

Find out why .NET programmers may want to learn and use Ruby, and discover the core syntax of the language.




Application Security Testing: An Integral Part of DevOps

Basic Types
A programming language wouldn't really be worth much if it couldn't manipulate numbers. Simple arithmetic is no trouble for Ruby:

irb(main):004:0> 3 + 4 => 7 irb(main):005:0> 3 * 4 => 12 irb(main):006:0> 3 - 4 => -1 irb(main):007:0> 3 / 4 => 0 irb(main):008:0> 3.0 / 4.0 => 0.75 irb(main):009:0> 0xF => 15 irb(main):010:0> 0x3 * 0xA => 30

As you can see, Ruby has support for integer and floating point types, and even accepts the common format for hexadecimal integers, although the result of 0x3 * 0xA was printed in decimal (30 rather than 0x1E).

As with .NET, numbers are actually objects, so you can call methods on them:

irb(main):011:0> 14.to_s => "14"

Don't try that with C++.

To to_s method converts an object into a string, so calling 14.to_s returns the string "14." As with .NET's ToString() method, the to_s method is actually a method on Object, so you can convert everything in Ruby to a string.

Ruby's strings have the full complement of operations that you might expect:

irb(main):012:0> "hello" + "there" => "hellothere" irb(main):013:0> "Reader".length => 6 irb(main):014:0> "Reader".reverse => "redaeR" irb(main):015:0> "reader".capitalize => "Reader" irb(main):016:0> "Reader".include?("foo") => false irb(main):017:0> "Reader".include?("ade") => true irb(main):018:0> " Reader ".strip => "Reader" irb(main):019:0> "Reader".gsub("e", "f") => "Rfadfr" irb(main):020:0> "Reader".delete("ea") => "Rdr" irb(main):021:0> "a" < "b" => true

Several string operations are available that you're probably not familiar with. For example, the following code tests whether a string lies between two other strings, alphabetically:

irb(main):022:0> "Bob".between? "Adam", "Chris" => true

The multiplication operator causes a string to repeat a specified number of times:

irb(main):023:0> "hi" * 5 => "hihihihihi"

The crypt method provides a salted one-way hash of the given string, which is useful for storing sensitive data like passwords:

irb(main):024:0> "Reader".crypt("ab") => "abofgDjq6JNJo"

Ruby doesn't have a built-in character type. It represents characters as numeric values. You can represent character constants with the ? syntax. You can use the chr method to convert a number into the string equivalent of its character:

irb(main):025:0> "Reader"[2] => 97 irb(main):026:0> ?a => 97 irb(main):027:0> 97.chr => "a"

It's not really helpful to just perform operations unless you can store the results for later use:

irb(main):028:0> x = 42 => 42

Strings have a special syntax that allows embedded evaluation. This evaluation isn't limited to just simple variable replacement, either: it's a full evaluation:

irb(main):029:0> "The answer is #{x}!" => "The answer is 42!" irb(main):030:0> "The answer is #{6 * 7}!" => "The answer is 42!"

You can avoid the evaluation by surrounding your string with single quotes instead of double quotes:

irb(main):031:0> 'The answer is #{x}!' => "The answer is \#{x}!"

Arrays in Ruby work much like the ArrayList class from .NET 1.0. They are variable-sized arrays that can store any type of data, indexed starting with 0:

irb(main):032:0> a = ["hello", 42, "world"] => ["hello", 42, "world"] irb(main):033:0> a << 5.0 * 7.5 => ["hello", 42, "world", 37.5] irb(main):034:0> a[0] => "hello" irb(main):035:0> a[6] = 'hi' * 2 => "hihi" irb(main):036:0> a => ["hello", 42, "world", 37.5, nil, nil, "hihi"] irb(main):037:0> a[99] => nil

The preceding code shows how to use the push operator (<<) to add items to the end of the array, and the index operator ([]) to both get and set values. When you add an item past the end of the array, Ruby fills in the "holes" in the array with nil values. When you attempt to access values beyond the end of the array, Ruby returns nil rather than throwing an exception.

You can slice off part of the array by using a ranged index. You can also combine this with the ability to use negative indices to access the array from the back rather than the front (where -1 is the last item, -2 is the second to last item, etc.). Although you can't use reverse ranges to get reversed slices, you can use a forward range, and then call the reverse method afterward:

irb(main):038:0> a[-1] => "hihi" irb(main):039:0> a[1..3] => [42, "world", 37.5] irb(main):040:0> a[2..-2] => ["world", 37.5, nil, nil] irb(main):041:0> a[-4..-1] => [37.5, nil, nil, "hihi"] irb(main):042:0> a[-1..-4] # Won't work => [] irb(main):043:0> a[-4..-1].reverse # Works fine => ["hihi", nil, nil, 37.5]

Like strings, you'll find several unique and useful methods available to arrays:

irb(main):044:0> a => ["hello", 42, "world", 37.5, nil, nil, "hihi"] irb(main):045:0> a.compact => ["hello", 42, "world", 37.5, "hihi"] irb(main):046:0> a.join => "hello42world37.5hihi" irb(main):047:0> [10, 75, 6, 29].sort => [6, 10, 29, 75] irb(main):048:0> [[1, 2, 3], [4, 5, 6]] => [[1, 2, 3], [4, 5, 6]] irb(main):049:0> [[1, 2, 3], [4, 5, 6]].flatten => [1, 2, 3, 4, 5, 6]

The final core data structure in Ruby is the Hash, similar to .NET 1.0's Hashtable. It is an associative array, where the indices (keys) can be any kind of value, and the data they point to (values) can also be any kind of data. In practice, most Hashes use symbols for keys (see the following section).

You declare hashes using the {} syntax, and you declare initialization values in "key => value" form. You can use the index operators to both get and set values in the hash:

irb(main):050:0> h = {:foo=>'bar', :baz=>'biff'} => {:foo=>"bar", :baz=>"biff"} irb(main):051:0> h[:foo] => "bar" irb(main):052:0> h[:unknown] => nil irb(main):053:0> h[:baz] = "new" => "new" => {:foo=>"bar", :baz=>"new"} irb(main):054:0> h.entries => [[:foo, "bar"], [:baz, "new"]]

Variable (and method) names in Ruby start with a lowercase letter, and can contain letters, numbers, and underscores.

Local variables have no prefix. Instance variables are prefixed with @. Global variables are prefixed with $.

You do not need to declare variables before you use them. Uninitialized variables have the value nil.

There are several pre-defined variables:

  • nil is an object that represents nothing (comparable to null in .NET, except that nil is an instance of the NilClass class).
  • true and false are instances of the TrueClass and FalseClass.
  • self, when used from a method, is a pointer to the object instance from which the method was called. When it is used from within a class, it refers to an instance of the class object itself.
  • __FILE__ and __LINE__ return the currently executing file and the line number in that file.
Ruby has a special kind of string known as a Symbol. Because strings can be changed in Ruby, using them as hash keys can be slow at best and unpredictable at worst.

The names of symbols follow the same rules as variables, except that they start with a colon (:). You can't change the value of a symbol, and two symbols with the same name have the same identity, which makes them excellent hash keys; instead of comparing the value of a variable length string, a lookup requires only comparisons against integer values.

Everything in Ruby is an object, and objects are all instances of classes. To discover what class something is, call the class method on it:

5.class => Fixnum (2 ** 96).class => Bignum 7.5.class => Float (1..10).class => Range "foo".class => String /^foo[a-e]$/.class => Regexp :foo.class => Symbol [].class => Array {}.class => Hash

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date