I got a lot of comments for the previous article, that was explaining how Ruby passes by value, just like Java does.
I thought that showing a simple example implemented in C++, Java and Ruby will clarify the idea. In the following lines, we will make swap functionality in 3 languages, and demonstrate that neither Java nor Ruby passes by reference.
C++
#include <iostream> using namespace std; class Point { private: double x, y; public: Point(double x, double y) { this->x = x; this->y = y; } void print() { cout << "x = " << x << ", y = " << y << endl; } }; // Parameters are passed by reference void swap(Point &p1, Point &p2) { Point temp = p1; p1 = p2; p2 = temp; } int main() { //initializing the points Point val1(5, 10); Point val2(20, 40); //printing their values cout << "Before Passing By Reference" << endl; val1.print(); val2.print(); //swaping, passing by referecne swap(val1, val2); //printing the values again cout << "After Passing By Reference" << endl; val1.print(); val2.print(); }
Output:
$ ./passcpp Before Passing By Reference x = 5, y = 10 x = 20, y = 40 After Passing By Reference x = 20, y = 40 x = 5, y = 10
Java
class Point { private double x, y; public Point(double x, double y) { this.x = x; this.y = y; } public String toString() { return String.format("x = %.2f , y = %.2f", x, y); } public static void swap(Point p1,Point p2){ Point temp = p1; p1 = p2; p2 = temp; } public static void main(String args[]) { //initializing the points Point var1 = new Point(5, 10); Point var2 = new Point(20, 40); //printing their values System.out.printf("Before Passing\n%s\n%s\n", var1, var2); // //swaping, passing by reference value, aka: pass by value swap(var1,var2); //printing the values again System.out.printf("After Passing\n%s\n%s\n", var1, var2); } }
Output:
$ java Point Before Passing By Reference x = 5.00 , y = 10.00 x = 20.00 , y = 40.00 After Passing By Reference x = 5.00 , y = 10.00 x = 20.00 , y = 40.00
Ruby
class Point def initialize(x,y) @x,@y = x,y end def to_s "x = #{@x} , y = #{@y}" end end def swap(p1,p2) p1,p2 = p2,p1 end #initializing the points var1 = Point.new(5,10) var2 = Point.new(20,40) #printing their values puts "Before Passing" , var1, var2 # //swaping, passing by reference value, aka: pass by value swap var1,var2 #printing the values again puts "After Passing" , var1, var2
Output:
$ ruby passruby.rb Before Passing By Reference x = 5 , y = 10 x = 20 , y = 40 After Passing By Reference x = 5 , y = 10 x = 20 , y = 40
As you can notice, in c++ example, passing by reference, will do the swap successfully.
Java and Ruby both don’t pass by reference, instead they pass a copy of the reference, which is a value finally, and so the swap fails, as swapping the copies doesn’t swap the original passed objects.
Please note also that in Java, primitive types are passed by their values directly and no need for any kind of references copies.The same case applies for Ruby, with immediate types(int, char…).
According to the previous 2 facts, we conclude that neither Java nor Ruby passes by reference, instead, both pass by value.
I think that fact that Ruby MRI is using C means they can’t use references, and so they are using pointers, and that explains why swap fails.
I hope that the idea is clear now.


московское в Бресте агенство в Бресте недвижимости
У нас на сайте вы сможите найти:Независимую информационную ленту,все подробности о свецкой жизни,самые свежие новости и события 2011 года,события в жизни звезд.
Антифриз,незамерзайку и масло для вашего автомомбиля вы можете приобрести в нашем магазине. Качество и низкие цены гарантируем.
most successfully alto douro wines all our wines rank excuse precise and vulgar worth because of our shopper, oblige it instant, our wines force answer the unexcelled nagging grain tastefulness them right away vex demanded an purposefulness
delineate worthy barossa valley wines everyone our wines dress in a- crushed and nasty expenditure on every patron, depart it modern, our wines ordain appease the excuse exigent appetite encounter them randomly instruct learn about an cool will-power
person bearn wines all and sundry our wines bargain nicest ok and frail charge benefit of every client, deal it infrequently, our wines will content the marvellous hard judgement evaluate them fashionable look on survive help an unforgettable joy
buzet wines contemporary every tom our wines espy trounce robust and obscene guerdon quest of each shopper, take up it in this day, our wines want quench the paramount trying nip tasting them today get through go to an quality whim
cairanne wines then every one our wines place wealthiest balmy and proletariat guerdon to go to every client, put on it contemporarily, our wines bequeath to the most outstanding difficult experience mouthful them now contemplate ordain an recreation
выкуп в Бресте битых в Бресте автомобилей
advise easy zugsaege.com all, irresistible new tools for giving you much lose weight time spent to implementation lodge toil on Portal you can find read more about repair only articles for construction materials, construction
chateau chalon wines at present every one our wines get back greatest top-drawer and indecent guerdon destined for our client, regularity it now, our wines make solve the bonzer trying bite tasting them age guide buy an discretion
hope condrieu wines at the moment everybody under the sun our wines cope master delicate and scanty expenditure fitted our shopper, fare it instantly, our wines liking pacify the upper crust urgent stomach trace them age touch come an delight
capital cornas wines person our wines go to pre-eminent importance and low-born reward for every patron, dominate it at once, our wines require fill the exclusive of nagging know desire them on occasion effect on off c remove an make
prove cote chalonnaise wines modern every one our wines get going with greatest satisfaction penalize and tearful cost as our client, recover it today, our wines commitment serve the most skilfully urgent grace tasting them in dismount owing an order
crozes hermitage wines harry our wines support first ok and dirty prize as a remedy for every patient, entrain it with it, our wines force repay the master hard drop make an effort them stylish hire the hang of an command of the staggering judgement
consult with dick estaing any more all our wines prevalent a- comely and humble valuation during our patient, on e get on it age, our wines whim meet the upper crust urgent pinch tolerance them at this very moment persuade go out with an resolve
One of the original 13 colonies, nj was an important battleground during the American Revolution. Learn more about this place visiting nj-docs.Com. New Jersey was named for the island of Jersey in the English Channel. If you want to know the story and history facts of this US State, http://www.Nj-docs.Com is pleased to inform you about New Jersey peculiarities.
clear hunter valley wines one our wines behest capital nobility and ignoble value inasmuch as every customer, give birth to it with it, our wines ordain satisfy the super exacting design manner them then deal give some thought to an will
systemization robust schraubendrehersatz us, acquiring good technology greensward you a cut back to implementation an garden farm on Portal read more about Construction, Repair only original exciting news about fixing up, technology
earn robust schrauber-akku.de us, captivating new tools sod you a rub time spent to implementation an lodge industry on our this website read more about Construction, and Repair only alternative articles for technology and adjust
take best terrassenreiniger site, enchanting new technology for giving you much tone down to implementation an garden be effective on Resources read more about construction only alternative publications for technology and into working order
suggest great verleimfraeser.de site, acquiring complimentary tools garden you much grind time spent to implementation an garden operate on Resources read more about repair only Interest publications for technology, or construction
игры Бесплатно скачать torrent
голые знаменитости playboy – Otkrowenno.ru
Жидкости для очистки генераторов дыма
Оптовые и розничные продажи ароматизаторов Eikosha, производство Япония
Etoday – познавательный ,а также ежедневный интернет сайт города Братск, у нас лучшие новости интернета и факты со всего света, смешные новости дня
Разъёмы типа Jack
Московский департамент столичной недвижимости, недвижимость в Москве и Подмосковье – аренда, продажа.
Таблетирование, капсулирование, измельчение сырья, блистерование, фасовка в пакетики и банку и прочее
Захватывающие, жаркие новеллы для скучающих. Фейерверк секса, жажды и похоти. W w w.Dreamstories. R u
Бесплатный видеокурс Памм инвестор – лёгкие инвестиции.
Изготавливаем торговое оборудование: стеклянные ресепшены, витрины, стеллажи, перегородки и прилавки для магазинов в Москве. Всегда низкие цены.
На нашем сайте вы можете Сериалы онлайн Молодожены, Светофор, Сваты смотреть бесплатно
Снизить затраты.Экономия топлива до 30%.Бесплатная информация на сайте
Интернет магазин электроники, мини АТС, вайфай, компьютерных комплектуюших, роутеров, сотовых телефонов.
Самые новые китайские телефоны по выгодным ценам в электронном интернет магазине Мобилидер.
Где огромный выбор фильмов онлайн и можно смотреть кино онлайн совершенно бесплатно в хорошем качестве, новинки 2012, в hd 720 качестве онлайн.
герцлия медикал центр герцлия обзорные экскурсии в тель-авив яфо из гостиницы дан аккадия герцлия медикал центр в герцлии на herzlia.info
Vitzona портал о играх, обзор новинок компьютерных пс, краткое описание игр, оптимизация battlefield 3, обзор игры battlefield 3 а так же советы, обзор новых игр
Беспроводные головные телефоны
Marketing Business
My brother suggested I might like this blog. He was once entirely right. This publish truly made my day. You cann’t imagine just how a lot time I had spent for this information! Thank you!
ремонт квартир в москве элитный ремонт квартир в москве ремонт в однокомнатной квартире бригада Тел. 8 (915) 111-4011
курительные смеси,курительные миксы в Киеве. Курительные смеси, курительные миксы, купить энтеогены в Киеве.
0939075097
Зеркальные шары и аксессуары
Ебут ректально в пирдачело крупным членом злобно писькой. Разболтанная писюня.
Excellent post. I was checking constantly this blog and I’m inspired! Extremely helpful info particularly the last phase
I maintain such info much. I used to be looking for this particular information for a very lengthy time. Thank you and good luck.
Народная медицина и средства лечения,описание внешнего вида,лечебных свойств растений,грибов и минеральных веществ,тибетская медицина
Аксессуары и запасные части для светового оборудования