10 reasons to upgrade to Ruby

Original author: h3raLd
  • Transfer
I met Ruby relatively recently, thanks to the wonderful Ruby on Rails framework . I do not consider myself an expert in Ruby, but I read PickAxe, wrote several utilities in Ruby for personal use, and also develop on Rails in my free time.

Ruby at the moment, my main language. I started with TurboPascal at school, studied C and C ++ at the university, wrote dissertations in Java , and I also learned PHP from scratch, because I wanted to learn how to make websites quickly and easily. I think that writing code for me is a form of entertainment, and then everything else. In the beginning I had some thoughts about which language to learn, Pythonor Ruby. I chose the second one because I did not want the wrong indentation to cause problems in my code.

There are a whole bunch of introductions, tutorials, articles, and essays written by gurus on how to get the most out of Ruby. This article is nothing like that.

This is a more modest, incomplete list of reasons that may (or may not) prompt you to use Ruby, or, in extreme cases, play with it. Caution: if you use a different programming language for work or for other purposes - do not complain to me if you no longer want to use it. This is exactly what happened to me, but for me it is not so important. Ruby is a wonderful and elegant language and like many similar things, it can capture your mind and break your soul.

In short, you are warned.

Why learn Ruby?


1. You get all the amenities (pleasure) without tricks.


Ruby has borrowed all the best from other programming languages, from smalltalk to Java , from Perl to Python . Here are the basic features that you basically could see in other languages:
  • Exceptions Believe it or not, exceptions are one of the most important things when developing programs of any kind. Programmers in PHP4 do not know anything about them and will tell you that you can simply print (errors) on the screen or use their own “super-duper” class to handle errors. Fortunately for all of us, Ruby comes with try / catch (or even better begin / rescue ) blocks and a set of predefined, extensible Exceptions to handle errors correctly.
  • Namespaces: Ruby modules make using the namespace easy; C ++ and Java enthusiasts should like this .
  • Built-in regular twists: For all Perl experts , you can enclose something in // and it becomes a regular expression, ready for comparison (for this we use the operator = ~ ).
  • Operator overloading: Ruby allows you to define operators such as +, -,> , etc. for any of your class.
  • Packages: called " gems " (pebbles), they really justify their name, in addition - they work. Packages support dependencies, and can also be cross-platform or platform-dependent.
  • Interactive console: can be used to test code interactively, like the Python console


2.You will love the little things.


Ruby is elegant. Why? Because he does not try to make the code concise so that it would interfere with readability and understanding. There are some tips that can help you:
  • You can use both operators, if and unless in conditional expressions. Of course, you can use if with the opposite value of the expression, but using unless usually leads to fewer errors. In addition, you can use both operators as conditional modifiers, putting them after the expression, and not before:order.new unless order.exists
  • You can use question marks and exclamations at the end of the method name. This agreement is not imposed, but the sign “ ? " Is used when the method returns true or false , while the" ! "Is used for methods that do something irreversible, like removing an entry from a database, removing the last character from a string, etc.
  • You can use aliases ( alias ) for the already existing methods. In this way, exist and exists methods can be obtained , without overhead and without repetition.
  • You can use the attr_reader , attr_writer, or attr_accessor directives to automatically create getter / setteer for class members.
  • And some other naming convention: constants, classes and modules are capitalized, methods and class members must start with a small letter, global variables are named starting with " $ ", object variable names begin with " @ ", and class variable names with " @@ ", etc.
  • When calling methods, you do not have to write brackets. You can write write File.open("/home/h3rald/test.txt")or simply File.open "/home/h3rald/test.txt", which is especially convenient with methods, without arguments.


3. You no longer need to use a semicolon.


Want to write the following instructions? Just jump to a new line. Press " Enter " and you're done. In Ruby, as in Python , the new line separates the instructions, so you don’t have to put a semicolon all the time. Unfortunately, this means that, like C ++ fans , we won’t be able to write a program in one line. But that's not so bad, is it?

4. Everything is an object, as it should be.


When I was learning Java , I was told that everything is an object.
- "Che, 14 and 374346.678 - objects?"
“No, silly, these are numbers!”

In Ruby, numbers, characters, Boolean values, and everything else is an object. Seriously. This means that you can write things like these:,
"YOU SHOULDN'T ALWAYS USE CAPITALS".lowcase # вернет "you shouldn't always use capitals"instead of something like this: By doing this you save time, save brackets, and so more logically.
# PHP Code
strtolower("YOU SHOULDN'T ALWAYS USE CAPITALS")



5. Everything matters.


Or "no longer need to use return to return values." If it’s quick, then this: all instructions in Ruby return a value, even assigning variables, so you really don’t need to use the “ return ” keyword at the end of the methods. The value of the last assignment will always be returned.

6. You can change the environment in any way possible.


The first time I saw this, I was impressed. Imagine a typical situation: you began to use a system class or a class written by someone else and realized that you need some additional method in it. There are several ways to solve this problem in typical programming languages:
  • You change the source code of the class if you have access to it. But usually this is a bad idea, do not do this.
  • You inherit your class from that and add a new method to it. This is usually a good idea. But due to one method, this may turn out to be somewhat mono-shaped. In addition, you will have to slightly correct your other code accordingly.
  • You can simply create a method outside the class. It will work, but it will not be very elegant, and yet - goes against the OOP .

In Ruby, you can add a method to the original class without editing the source code. This can be done even for the system class.
We want to add a method to convert values ​​from meters to feet? Just extend the Numeric class , as shown: From now on, all of our numbers will have a new method that can be used like any other: Classes in Ruby never close and can be extended at any time, from anywhere. Naturally, you must use this opportunity with caution!
class Numeric
def feet
self*3.2808399
end
end


5.feet # возвратит 16.4041995


7.You cannot get unicorns from birds and end, but you will get donkeys if you want.


I clearly remember how my C ++ teacher used animals to illustrate the basic concepts of object-oriented programming — classes and inheritance. It was something mysterious when she explained to us multiple inheritance, forming “Pegasus” from “birds” and “horses”. Crazy stuff, Ruby does not allow multiple inheritance. It looks like a trend and in the end it is a matter of taste. I am not happy with multiple inheritance, as this can lead to unpredictable things. Despite this, it is possible to create something similar using Ruby modules , so that the variables and methods of one module will be added to a specific class if the module is included in it.

8. XML - really unnecessary.


XML is a beautiful, common, markup language that can be processed by all programming languages ​​and is used universally. Unfortunately, it is too cumbersome to write, difficult to process (parsing) and, let's be honest - difficult to read in most cases. But take a look at the following snippet: It is certainly easier and simpler than XML , right? Welcome to YAML , your favorite (but not the only) Ruby markup language , with the help of which any object can be represented in a simple, concise, but complete form. Ruby is able to work with XML , but the simplicity of YAML has bribed many developers who now use it instead of XML
regexp: !ruby/regexp /a-zA-Z/
number: 4.
string: a string


, for example for configuration files (this is what Rails did ). The fragment presented above was obtained by executing the following code fragment:
{"string" => "a string", "number" => 4.7, "regexp" => /a-zA-Z/}.to_yaml
The to_yaml method is defined for the Object class , which is the parent for all other objects, and therefore is available for all Ruby objects . This allows you to convert objects to YAML and vice versa, absolutely transparent to the developer. Cool, yeah?

9. Lambda is more than just a Greek letter.


Ruby borrowed some magic from Lisp and Perl into Proc objects and blocks . Proc is a “block of code associated with a set of local variables. Once connected, they can be called in various contexts and still access those variables. ” Let's look at the following: You could use the lambda keyword instead of Proc.new , this does not affect the result. It might seem familiar to people who know Perl and Python (or Lisp ). This can even be done in PHP , but not many people use this opportunity. Also in Ruby
def gen_times(factor)
return Proc.new {|n| n*factor }
end

times3 = gen_times(3)
times5 = gen_times(5)

times3.call(12) #=> 36
times5.call(5) #=> 25
times3.call(times5.call(4)) #=> 60


Uncreated Proc blocks are widely used , for example, to iterate over the contents of an object and execute some code, similar to the each method available for the Array class :
[1, 2, 4, 6, 8].each {|c| puts c*2} #=> возвратит каждый элемент, умноженный на 2
If the code does not fit on one line, it is recommended to use the do ... end construct instead of using parentheses. Ruby fans don't like brackets.

10. You can use Rails.


Last but not least ... you can always use Rails to develop web applications. Development will not be as easy as with PHP , but Rails was written in Ruby because it has features that are not available in other languages.

Conclusion


Time is over. Maybe you are already thinking about looking at Ruby , maybe you have already tried it, or maybe you just ignored it. Whatever the case, the next time you look at your code, it will seem scary, and its size is awesome - do not blame me.



Dear Readers - do not forget that the habrayuzer just translated (lousy, yes) the text. There is no need for him to express ideological claims.

Also popular now: