Comparing Ruby and C#: Equality

Beauty

While reading The Ruby Programming Language I wrote a couple of notes about the language comparing it to C#. This is the first post of the series talking about those notes.

C# and Ruby share a similar syntax to compare equality in objects. Both use the operator equals (==) and, at least, one method to compare. Ruby uses equal? and eql?, C# uses Equals. Also, both support overriding the equals (==) operator to provide a different logic in case that’s required. The methods’ name are different but they work pretty much the same.

Understanding the difference between both languages is really simple. If you already know the difference between reference types and values types you are pretty much all set.

Ruby

Method equal?

Method used to test reference equality in two objects. For example:

#!/usr/bin/env ruby

a = 0
b = 0.0
c = b
d = e = 0

# "false" pointer c points to b, and b and a
# are different types.w
puts "c.equal?(a) #{c.equal?(a)}"
# "false" b and a are different types
puts "b.equal?(a) #{b.equal?(a)}"
# "true" Same type, same value.
puts "d.equal?(e) #{d.equal?(e)}"

Method eql?

Synonym of equal?, not strict type conversion. Notice Hash classes uses this method for creating the hash, so if two values are the same the hash method should return the same value.

#!/usr/bin/env ruby

a = 0
b = 0.0
c = b
d = e = 0

# "false" Pointer c points to b, and b and a are different types
puts "c.eql?(a) #{c.eql?(a)}"
# "false" Different types
puts "b.eql?(a) #{b.eql?(a)}"
# "true" Same type, same value.
puts "d.eql?(e) #{d.eql?(e)}"

Operator equals (==)

By default, in Object class, it’s a synonym of equal?. Tests reference equality.

#!/usr/bin/env ruby

a = 0
b = 0.0
c = b
d = e = 0

# "true" Even when pointer c points to b, and b and a
# are different types, the value is the same
puts "c == a #{c == a}"
# "true" Type is casted to allow comparing them
puts "b == a #{b == a}"
# "true" Same type, same value.
puts "d == e #{d == e}"

C#

Before explaining the equality options, notice one important difference between Ruby and C#.

First, Ruby is a dynamic typed language. When declaring variables there’s no meaning of variable type, all variables can be used to identify instances of different types depending on the situation. For example, we can define a variable x to act as a string, and then use the same variable x to act as an integer, this doesn’t mean we are converting the string to integer, this means we are using the same pointer (variable x) for two different types, string and integer, pointing to two different addresses in memory. For example:

#!/usr/bin/env ruby

a = "I'm string"
# Output: "a Value: 'I'm string' Class: 'String'"
puts "a Value: '#{a}' Class: '#{a.class}'"

# Output: "a Value: '10.0' Class: 'Float'"
a = 10.0
puts "a Value: '#{a}' Class: '#{a.class}'"

C# is a static typed language, all variables must indicate their type before instantiating an object. For example, when declaring a variable x of type string, you will be able to create an instance of string, only, there’s no way to “reuse” x as an integer in the same scope. Try to compile the following example, it will fail:

public class RubyAndCSharp {

	public static void Main (string []args) {
		string x = "I'm string";
		System.Console.WriteLine ("a Value: '{0}' Class: '{1}'", x, x.GetType ());

		x = 10.0; // It will fail here: "error CS0029: Cannot implicitly convert type `double' to `string'"
		System.Console.WriteLine ("a Value: '{0}' Class: '{1}'", x, x.GetType ());
	}
}

Second, memory management. Both languages manage memory automatically: by default all memory is created and released automatically, there is no need to explicitly release or allocate memory, unless the programmer wants to do so. However, in C# there’s a “difference” between types. There are two type categories: Value Type and Reference Type. The difference, related to memory use, is the way they work and the addresses in memory they use. Declaring value types automatically allocates memory, declaring reference types declares a pointer and the memory is allocated when the object pointed by the variable is instantiated. The Value Types are allocated in the stack and the Reference Types are allocated in the heap.

This difference is really important. Comparing two instances of objects with different “category”, one value type and one reference type, does not work, it just fails. Is like comparing an apple to an orange. Is comparing a value stored in the stack to a value stored in the heap. We can’t compare them without writing any extra code.

And this extra code means using the base class object as the pointer for different types, because both types, value type and reference type, are subclasses of object, in one way or another. Let’s try to compile the following example:

public class RubyAndCSharp {

	public static void Main (string []args) {
		object x = "I'm string";
		// Output: "a Value: 'I'm string' Class: 'System.String'"
		System.Console.WriteLine ("a Value: '{0}' Class: '{1}'", x, x.GetType ());

		x = 10.0;
		// Output: "a Value: '10' Class: 'System.Double'"
		System.Console.WriteLine ("a Value: '{0}' Class: '{1}'", x, x.GetType ());
	}
}

After this short (or long?) explanation we are ready to see talk about the methods.

Method Object.Equals()

Is used to test reference equality in reference types and bitwise equality in value types. For example:

public class RubyAndCSharp {

	class MyClass {
		public string Name { get; set; }
		public override string ToString () { return Name; }
	}

	public static void Main (string []args) {
		// object.Equals in Reference Types uses address memory
		MyClass myClass0 = new MyClass () { Name = "test" };
		MyClass myClass1 = myClass0;

		System.Console.WriteLine ("object.Equals('{0}','{1}') = {2}", myClass0, myClass1, object.Equals (myClass0, myClass1));

		// Let's try again. This will return false. myClass1 and myClass2 are different instances
		myClass1 = new MyClass () { Name = "test" };

		System.Console.WriteLine ("object.Equals('{0}','{1}') = {2}", myClass0, myClass1, object.Equals (myClass0, myClass1));

		// It doesn't matter myInt0 and myInt1 are different variables, equality will be true.
		int myInt0 = 1;
		int myInt1 = 1;

		System.Console.WriteLine ("object.Equals('{0}','{1}') = {2}", myInt0, myInt1, object.Equals (myInt0, myInt1));
	}
}

Operator equals (==)

Is, basically, a synonym of object.Equals, same rules apply.

public class RubyAndCSharp {

	class MyClass {
		public string Name { get; set; }
		public override string ToString () { return Name; }
	}

	public static void Main (string []args) {
		// == in Reference Types uses address memory
		MyClass myClass0 = new MyClass () { Name = "test" };
		MyClass myClass1 = myClass0;

		System.Console.WriteLine ("object.Equals('{0}','{1}') = {2}", myClass0, myClass1, myClass0 == myClass1);

		// Let's try again. This will return false. myClass1 and myClass2 are different instances
		myClass1 = new MyClass () { Name = "test" };

		System.Console.WriteLine ("object.Equals('{0}','{1}') = {2}", myClass0, myClass1, myClass0 == myClass1);

		// It doesn't matter myInt0 and myInt1 are different variables
		int myInt0 = 1;
		int myInt1 = 1;

		System.Console.WriteLine ("object.Equals('{0}','{1}') = {2}", myInt0, myInt1, myInt0 == myInt1);
	}
}

Operator Object.ReferenceEquals()

Pretty straightforward, tests reference:

public class RubyAndCSharp {

	class MyClass {
		public string Name { get; set; }
		public override string ToString () { return Name; }
	}

	public static void Main (string []args) {
		// Object.ReferenceEquals in Reference Types uses address memory
		MyClass myClass0 = new MyClass () { Name = "test" };
		MyClass myClass1 = myClass0;

		System.Console.WriteLine ("object.Equals('{0}','{1}') = {2}", myClass0, myClass1, System.Object.ReferenceEquals (myClass0, myClass1));

		// Let's try again. This will return false. myClass1 and myClass2 are different instances
		myClass1 = new MyClass () { Name = "test" };

		System.Console.WriteLine ("object.Equals('{0}','{1}') = {2}", myClass0, myClass1, System.Object.ReferenceEquals (myClass0, myClass1));

		// This will also return false.
		int myInt0 = 1;
		int myInt1 = 1;

		System.Console.WriteLine ("object.Equals('{0}','{1}') = {2}", myInt0, myInt1, System.Object.ReferenceEquals (myInt0, myInt1));
	}
}

Colophon

Sometimes you will have to use an object reference to refer to both types, value and reference, if you are planning to compare their value you have to use the static method object.Equals(a,b). Using the operator equals (==) will always return false, because of the boxing/unboxing:

public class RubyAndCSharp {

	public static void Main (string []args) {
		string str0 = "hola";
		string str1 = "hola";

		object obj0 = str0;
		object obj1 = str1;

		System.Console.WriteLine ("Equals: {0}, Using ==: {1}, object.Equals {2}",
		                          obj0.Equals (obj1), // True
		                          obj0 == obj1, // True
		                          object.Equals (obj0, obj1)); // True

		bool bool0 = true;
		bool bool1 = true;

		obj0 = bool0;
		obj1 = bool1;

		System.Console.WriteLine ("Equals: {0}, ==: {1}, object.Equals {2}",
		                          obj0.Equals (obj1), // True
		                          obj0 == obj1, // False
		                          object.Equals (obj0, obj1)); // True

	}
}

Updated 2010-03-17: Thanks to sukru for noticing the error in the examples.

Updated 2010-03-18: Fixed typos, thanks to yoeri and doza noticing them.

Shorten URL: http://bit.ly/9Mvvgzshorten url

Parallel Development Environments? Pulque!

¡Quiero pulque!

By Claire L. Evans / CC BY-ND 2.0

This is an updated version of Multiple Parallel Mono Environments.

What is Pulque?

Pulque is a collection of applications written in Ruby and Bash scripting to maintain parallel development environments.

Why does Pulque exist?

Three reasons:

  1. I need to keep multiple versions installed of the same software,
  2. I need to know what Version Control System is used by the software, and the most important
  3. I want to keep myself sane.

At work, I have to interact with different open source projects, most of them use Subversion and Git, but some others use Bazaar and Mercurial. Keeping track of the current parallel development environment and the VCS used by the software is exhausting.

You spend time focusing on something that shouldn’t be that important:

  • Managing your parallel environments and,
  • Keeping track of the VCS used by the software

Is easy to get confused when interacting with the repository, for example, executing svn update when the software is stored in a git repository. Is silly, but it happens. Unless you are using an IDE that support Multiple Parallel Development Environments you will need the terminal to configure and build your projects.

Pulque helps you maintaining parallel development environments by:

  • Printing in the bash prompt the name of the parallel development environment and the type of the VCS, this information is updated depending on the working directory,
  • Defining aliases to the default commands used to configure and build the software project, to always prefix your projects using your parallel environment, and
  • Showing a failure or success alert when the command finishes.

Installing and using Pulque

Follow the instructions in INSTALL, or if you are using openSUSE 11.2:

OneClick Install
Click here to drink Pulque!

Don’t forget to add the function pswitch to your .bashrc. Bash will autocomplete your environment name when using TAB TAB.

function pswitch {
  source /usr/bin/__pswitch $1
}

Read the USING file to understand how to use Pulque in the daily basis. If you find something weird or interesting please create an issue to fix it.

Colophon

According to Wikipedia: “Pulque, or octli, is a milk-colored, somewhat viscous alcoholic beverage made from the fermented sap of the maguey plant, and is a traditional native beverage of Mexico.

Shorten URL: http://bit.ly/ay65poshorten url

The Ruby Programming Language

english — Tags: , , , , , , , , — @ 23:50

Ruby

A couple of days ago I finished reading: The Ruby Programming Language, book written by David Flanagan and Yukihiro Matsumoto. If I have to say anything about the book and, the language, of course, is: I am impressed. The syntax is pretty for writing and simple for reading. Its simplicity makes you understand the code, is like visualizing the goal of the program in your mind by reading it, not running it. It is like reading a well written letter. You just understand.

I must say, when I was reading the book, at the beginning. I did not feel comfortable with the weird, at that time, syntax. Method decorations such as “!” and “?”, and the support for methods aliases made no sense. Actually I thought I was wasting my time by trying to learn the language. I was wrong.

When I learned C++ several years ago, I did not have reference to object orientation or any object-oriented programming language. Learning it was difficult, but, at the same time, easy. Difficult because I did not know the paradigm, easy because it was my first time learning that kind of syntax. After learning C++ I decided to learn Java and after that, I decided to learn C#.

And I learned them all the same way. I “translated” the syntax. Translated it from the “new language” to the “old language”. I did learn them all. And I thought, for long time, that the rule was: “Learn all the languages the same way: by translation”. I was wrong. Again.

Learning a new programming language, in my opinion, is better when you do not translate the new language. Similar to learn to speak a new language. In both cases, you have to think in the language. I decided to think in the new language. To do it that way. The Ruby way. The results were amazing. Were so amazing that inspired me to write a project in Ruby. I wanted to try out the syntax, the platform and the community. To see if the language was that good as I thought.

After trying it out. No disappointments at all. Actually is interesting that C# and Ruby share a lot of things, syntactically speaking. Both of them are pretty languages. Probably they do not share goals. However, I’m sure they share one goal: to make the life of the software developer easier. And, to a software developer, a programming language, and everything around it, that makes your life easier is what matters the most.

Shorten URL: http://bit.ly/5drYK7shorten url
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2004-2010 Mario Carrion | powered by WordPress with Barecity