The best way to learn Rails. Best Way to Learn Rails Ruby Programming Language for Beginners

Ruby is a powerful and popular programming language. In addition to its popularity, a well-known framework is based on it, which allows you to create cool and dynamic websites of various subjects. If you look at the TIOBE ranking, then the language is among the twenty most popular languages ​​in the world.

The language appeared in 1995 and is considered a young language compared to C or C ++, which appeared in 1972 and 1983, respectively. The language has a number of advantages and specific features that are implemented exclusively in it, if we compare other popular programming languages.

Course plan

During the video course, you will learn the Ruby language without using additional frameworks. Additional courses on ruby you can find on .

During the course, we will learn how to install and work with the language, learn the syntax Ruby(variables, loops, conditional statements), as well as more complex things: OOP, working with files, exceptions, methods, and many other topics.


Installing Ruby on Windows

To install Ruby on Windows, use RubyInstaller, which can be downloaded from the official website at this link. Download latest version and install it like a normal program. After the installation is completed, you will see a similar window:

On this window, make sure that the checkbox is checked, then another application will open for installation ruby into the system.

In the window that opens, enter 1 in turn and press Enter, after waiting for the end of the installation, press 2 and Enter and at the end execute the third command by pressing 3 and Enter.

Installing Ruby on a Mac

On a Mac, Ruby is installed by default, so you don't need to do anything extra. You can check the language version in the terminal with the following command:

If the version is outdated, you can download a new one. First you need to download the Ruby version manager. This is done through the terminal with the command:

Curl -L https://get.rvm.io | bash -s stable

After installing the manager, restart the terminal. Run the following command:

Rvm list known

After restarting, you can install whatever version you want. In our case, version 2.4.2 was installed:

rvm install ruby-2.4.2

At the end, you can check the version again and if it is still old, then just set the default to the new version.

I have long wanted to learn Ruby on Rails on some basic level. No specific purpose. Rather, just for myself, in order to better understand what is so special about it (unlike 100,500 other technologies and frameworks), which allows you to quickly create and scale quite loaded Internet projects. A secondary reason was the desire to try new approaches to learning. When I was studying to be a programmer, we only had books and forums where you can ask for advice. Now there are interactive textbooks and online programming schools, a huge number of screencasts (almost a dream: to watch how gurus code), knowledge bases like stackoverflow.com and tons of source codes on GitHub, where you can spend hours studying the source codes of real pros. I decided to dedicate the next few nights (and there is no time during the day) to trying new ways of learning in action.

night one

It would be strange to start learning Ruby on Rails without at least a minimum knowledge of Ruby directly. I've taken on the ruby-lang.org interactive guide before. But as I passed it, I immediately forgot everything. Its creators promise that it will take fifteen minutes to walk through and master the Ruby syntax. It took me thirty. True, with constant distraction on Twitter. The process looks something like this. They tell you: “Arrays in Ruby are declared like this, and data is retrieved from arrays like this. Now let's try to make an array and extract N elements from it. And we'll check." You read how everything is arranged, and immediately try it. Ruby you, of course, will not learn. It is better to think of it as a super-express course that works.

Still, Ruby itself is very far from the Ruby on Rails framework. I wanted to master the rails. From our article about online education, I definitely remembered the sensational Zombie for Rails railsforzombies.org course. It's just like Try Ruby, an interactive tutorial that starts you off the bat to teach you how to prepare rail applications. First, they give you a mini-lecture (in English, but everything is very clear - turn on the subtitles) about the file structure of a rail application, the CRUD approach for working with data, explain how the MVC model is implemented in rails, and so on. After each video, you are offered to complete assignments to consolidate the material. Everything seems simple and understandable, the course flies by unnoticed in an hour or two (it is small). But! Did I feel after the course that I could write a rail application? Unfortunately no!

Night two

One of the reasons why after Rails for Zombies there is some basic knowledge, but no confidence, is the virtual environment in which the training takes place. On the one hand, it reduces the entry threshold to the limit: you don't have to worry about the environment. On the other hand, you don’t create anything real along the way - no “Hello World” for you at the end. And most importantly, from which side to approach its creation, it is not clear. From that moment on, I wanted to try Ruby on Rails in action, actually installing it on the system (before that, I didn’t even have to try), and create a simple application from scratch.

I do not remember how, but quite by accident I stumbled upon a very successful course of screencasts in Russian rails.hasbrains.org. Thanks to the author for a competent presentation: he methodically explains the principles of the rail application in detail, immersing you in all the necessary subtleties along the way. In short, the entire second night of the experiment, I watched the first half of over thirty episodes of these screencasts.

The picture finally stuck in my head, how the application is generated, how to work with the rail console, how to create models and migrations, how to update models and how to validate data in them, RESTful controllers, and so on. Watching each of the episodes, I immediately tried everything in action, building a fully working rail application. It became clear how the rails are arranged in principle.

Night three

On the third night, the last episodes of screencasts remained, which I managed to watch in one sitting: working with rails no longer seemed so wild. At this point, someone told me that the Rails for Zombies course has a sensible and much deeper continuation. True, the course is already paid and is hosted within the framework of the Code School www.codeschool.com programming school. Paying 25 bucks to get access to all the courses of the school was not a pity. This is the cost per month, so if you don't like it, don't forget to cancel your subscription.

The Rails for Zombies 2 course was really successful. True, a lot was a repetition of what I saw in the screencasts - but it was even kind of nice. Five levels and five blocks of exercises that you do right in the interactive console. By this point, the rails already seemed logical, understandable and usable.

In Code School, you can program directly in the browser by completing course assignments

What's next?

Have I learned to do complex projects? No. But I definitely realized the approaches used in the rails, and understood their convenience. I learned how to quickly create simple applications and increase its functionality in a super-short time using gems written by the community. I caught the courage and continue to study with pleasure the best practices in the Code School programs (now I'm watching the course on unit tests). And I am damn pleased that learning technology has become so easy.

"Hey! What are you doing?" - “Yes, I’ll program one thing in Ruby.” - "It's contagious:-)"
Here is a conversation I had today with a friend. Why Ruby?

Why Learn Ruby

This question concerns those who have been programming in PHP for a long time and successfully. You have mastered one language, which is great, but do not stop there. Many may object that they know the language, are oriented in nyoi and have already learned all the tricks with it. I will name a few reasons to learn Ruby.

  1. Curiosity. For example, it was very interesting for me to work with open classes. This is how to take and inject your method into the system class - in my opinion it's great. Will there be confusion? But how to do it? In general, everything new is interesting.
  2. . Because I've been programming in PHP for a long time, I'm wondering what Ruby can boast of in front of PHP /
  3. Ruby Speed. A twitter is made in Ruby (although it has been abandoned recently). I would like to test its performance in reality.
  4. Problem class. Ruby is good for web applications. Is that so?
  5. Metaprogramming. Perhaps the most important reason.

How to learn Ruby. Syllabus.

This is where my first mistake was that I started learning the framework without knowing the language. Now I understand that this is not necessary. Forgetting about Ruby on Rails for a while, I began to study Ruby itself, since a system task hung in the ticket system for a long time, which was hard to solve in php. I really didn't want to give it root permissions. So the plan is this.

  1. Functions, classes, public classes. Attributes (accessors and mutators).
  2. Working with strings, with arrays. Finding and replacing substrings, etc. Type conversion.
  3. Working with files.
  4. Working with the system environment.
  5. Application design, work with gems (modules).
  6. Working with DB.
  7. Installing Ruby on Rails, .

In this post, I will publish my first Ruby application and invite everyone to the discussion. Point out mistakes, offer best practice, ask questions.

Let's learn Ruby together!

Lesson 1. The first application in Ruby.

The task is this. There is DNS server on the hosting, and when calling the console utility in ruby, you need to add a zone for the domain, as well as a zone entry in the list of zones (domains.list) and change one entry in the database where to register this domain. Database access settings are stored in the php application, specifically in its INI file. After all the steps, you need to restart the DNS server (bind).

Workbench for Ruby

As an IDE, I will use RubyMine from JetBrains. I really liked them. Although it was about phpStorm, the quality is immediately visible. We install ruby ​​through RVM first for all users, then we set it up for root and our user.

Extending Ruby Public Classes

To work with INI files in Ruby, we use the gem inifile. But it has a small problem. In a ZF INI file, you can safely use constants, and the lines look like this:

IncludePaths = APPLICATION_PATH "/../vendors/Doctrine/"

Here from APPLICATION_INI then demolishes the gem parser. Specifically, this line does not fit any pattern:

@rgxp_comment = %r/\A\s*\z|\A\s*[#(@comment)]/ @rgxp_section = %r/\A\s*\[([^\]]+)\] /o @rgxp_param = %r/\A([^#(@param)]+)#(@param)\s*"?([^"]*)"?\z/

Here is the situation for using public classes. Let's replace the IniFile::parse function with our own. I will add all additions to the fucntion.rb file

Class IniFile private # # call-seq # parse # # Parse the ini file contents. # def parse return unless File.file?(@fn) section = nil tmp_value = "" tmp_param = "" fd = (RUBY_VERSION >= "1.9" && @encoding) ? File.open(@fn, "r", :encoding => @encoding) : File.open(@fn, "r") while line = fd.gets line = line.chomp # mutline start # create tmp variables to indicate that a multine has started # and the next lines of the ini file will be checked # against the other mutline rgxps. if line =~ @rgxp_multiline_start then tmp_param = $1.strip tmp_value = $2 + "\n" # the mutline end-delimiter is found # clear the tmp vars and add the param / value pair to the section elsif line =~ @rgxp_multiline_end && tmp_param != "" then section = tmp_value + $1 tmp_value, tmp_param = "", "" # anything else between multiline start and end elsif line =~ @rgxp_multiline_value && tmp_param != "" then tmp_value += $1 + "\n" # ignore blank lines and comment lines elsif line =~ @rgxp_comment then next # this is a section declaration elsif line =~ @rgxp_section then section = @ini[$1.strip] # otherwise we have a parameter elsif line =~ @rgxp_param then begin section[$1.strip] = $2.strip rescue NoMethodError raise Error, "parameter encountered before first section" end elsif line =~ %r/APPLICATION_/ then next else raise Error, "could not parse line "#(line)" end end # while ensure fd.close if defined?fd and fd end end

I'll also extend the String class to allow validation of domains.

Class String def valid_domain_name? domain_name = self.split(".") name = /(?:+)+/.match(domain_name).nil? tld = /(?:(2)|aero|ag|asia|at|be|biz|ca|cc|cn|com|de|edu|eu|fm|gov|gs|jobs|jp|in|info| me|mil|mobi|museum|ms|name|net|nu|nz|org|tc|tw|tv|uk|us|vg|ws)/.match(domain_name).nil? (domain_name.count > 1 and name != false and tld != false) end end

Sources

Well, now I'll show you the actual source.
index.rb

#coding: utf-8 require "mysql2" require "socket" require "inifile" require "./functions.rb" # Hash of server machine addresses hosts = ( :production => "83.168.22.1", :test => "84.22 .11.1" ) util = Util.new(hosts) util.releative_config_path="/site.com/application/config/application.ini" # Check parameters quit if (ARGV.count != 2) domain = ARGV hostname = ARGV. split(".") quit("Invalid domain name") if (not domain.valid_domain_name?) # Search for a company in the database result = Mysql2::Client.new(util.get_db_settings).query("SELECT id FROM `sites` WHERE `hostname` = "#(hostname)"") quit("Company not found") if result.count != 1 # Update its hostname rows = Array.new result.each(|row| rows<< row} company_id = rows["id"] result = Mysql2::Client.new(util.get_db_settings).query("UPDATE `dbname`.`sites` SET `domain` = "#{domain}" WHERE `dao_companies`.`id` =#{company_id};") # Добавление зоны bind_config_path = "/etc/bind" default_zone_file = bind_config_path + "/zones/DEFALT" new_zone_file = bind_config_path + "/zones/#{domain}.zone" zones_list_file = bind_config_path + "/domains.lst" quit("File with default zone does not exists") unless File.exist?(default_zone_file) quit("File with zones list does not exists") unless File.exist?(zones_list_file) zone = IO.read(default_zone_file).gsub("SERIAL",Time.now.strftime("%Y%m%d%S")).gsub("DOMAIN", domain) if not File.exist?(new_zone_file) then File.open(new_zone_file, "w") {|f| f.puts(zone) } else quit("Domain "+domain+" zone already exists!") end # Добавление зоны в список zone = "zone \"#{domain}\" { type master; file \"/etc/bind/zones/#{domain}.zone\"; };" if not IO.read(zones_list_file).include?(domain) then File.open(zones_list_file, "a") {|f| f.puts(zone) } end # Перезапуск сервисов (bind9) system("service bind9 restart") puts "Completed"

gemfile
This file describes the dependencies of the project.

Source:rubygems gem "mysql2", "0.2.6" gem "inifile"

Well, actually included functions.
functions.rb

#coding: utf-8 class String def valid_domain_name? domain_name = self.split(".") name = /(?:+)+/.match(domain_name).nil? tld = /(?:(2)|aero|ag|asia|at|be|biz|ca|cc|cn|com|de|edu|eu|fm|gov|gs|jobs|jp|in|info| me|mil|mobi|museum|ms|name|net|nu|nz|org|tc|tw|tv|uk|us|vg|ws)/.match(domain_name).nil? (domain_name.count > 1 and name != false and tld != false) end end class IniFile private # # call-seq # parse # # Parse the ini file contents. # def parse return unless File.file?(@fn) section = nil tmp_value = "" tmp_param = "" fd = (RUBY_VERSION >= "1.9" && @encoding) ? File.open(@fn, "r", :encoding => @encoding) : File.open(@fn, "r") while line = fd.gets line = line.chomp # mutline start # create tmp variables to indicate that a multine has started # and the next lines of the ini file will be checked # against the other mutline rgxps. if line =~ @rgxp_multiline_start then tmp_param = $1.strip tmp_value = $2 + "\n" # the mutline end-delimiter is found # clear the tmp vars and add the param / value pair to the section elsif line =~ @rgxp_multiline_end && tmp_param != "" then section = tmp_value + $1 tmp_value, tmp_param = "", "" # anything else between multiline start and end elsif line =~ @rgxp_multiline_value && tmp_param != "" then tmp_value += $1 + "\n" # ignore blank lines and comment lines elsif line =~ @rgxp_comment then next # this is a section declaration elsif line =~ @rgxp_section then section = @ini[$1.strip] # otherwise we have a parameter elsif line =~ @rgxp_param then begin section[$1.strip] = $2.strip rescue NoMethodError raise Error, "parameter encountered before first section" end elsif line =~ %r/APPLICATION_/ then next else raise Error, "could not parse line "#(line)" end end # while ensure fd.close if defined? fd and fd end end def quit(message=nil) banner = " === ========================== | DNS Addition tool | ============================ Usage: ruby ​​./index.rb domain.com olddomain.site.com" if not message.nil then banner = message end puts banner exit end class Util attr_accessor:hosts, :releative_config_path, :environment def initialize(hosts =Array.new) self.hosts = hosts end # Get the local IP address def local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect "64.233.187.99", 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end # Get environment def get_environment if @environment.nil? then hosts = self.hosts.invert if(hosts.include?(self.local_ip)) then @environment = hosts else @environment = "development" end else @environment.to_s end end def get_config_path local_username = get_local_username "/home/" +local_username+"/sandbox"+self.releative_config_path end # Returns the username if the utility is run via rvmsudo or directly def get_local_username if ENV["SUDO_USER"].nil? quit("Util should be run over rmvsudo, \r\nexample: rvmsudo ruby ​​./index.rb domain.ru some.subdomain.ru") else ENV["SUDO_USER"] end end def get_db_settings config = IniFile::load( self.get_config_path) section_name = self.get_environment.to_s + " : bootstrap" quit("No suitable section in config file") unless config.has_section?(section_name) dsn = config.to_h["resources.doctrinedata.connections.default. dsn"] # Parse dsn dsn.sub!("mysql://", "") arr = dsn.split("@") dbconfig = ( :username => arr.split(":"), :password = > arr.split(":"), :host => arr.split("/"), :database => arr.split("/") ) end end

But what about PHP?

This post is not about quitting PHP and learning ruby. PHP is the most popular web programming language, thousands of interesting things and algorithms are implemented on it, incl. even neural networks. And I love him) Over the years, you can say that I became related to him, despite all his shortcomings. But this does not mean that you should not learn something new for yourself.

Recently I have been asked the question of what books to learn Ruby from. I'm reading this one right now.

This book is the official guide to the dynamic programming language Ruby. The team of authors is truly stellar: David Flanagan is a well-known specialist in the field of programming, author of a number of best-selling books on JavaScript and Java; Yukihiro "Matz" Matsumoto is the creator and lead developer of Ruby.
The book provides a detailed description of all aspects of the language: the lexical and syntactic structure of Ruby, varieties of data and elementary expressions, definitions of methods, classes and modules. In addition, the book contains information about the Ruby platform APIs.

The publication will be of interest to experienced programmers who are getting acquainted with the new Ruby language, as well as those who are already programming in Ruby and want to achieve a higher level of understanding and workmanship. You can find a book on ozone or a biblio-globe.

I look forward to your comments on the code and any interesting ideas!)

Thanks!

If this article helped you, or if you want to support my research and blog, here's the best way to do so:

Guys fire, course fire, everything is fire!!! Starting from the very basics and moving on to more difficult things The course provides both a theoretical base and a lot of practice. The course is aimed at ensuring that the student builds the correct thinking in his head from the point of view of a programmer. I really liked this course, I advise everyone, both for beginners and those who are already familiar with the basics of programming. Thank you guys for their valuable work and experience!

Very good course - well done guys. Gradually, all the minimum necessary for the life of a programmer is put into the brain and they are still thrown with more advanced buns.

The presentation of the material is just fire, it was so interesting to watch all the videos and then go through the homework, only one phpshnik's recognition what is it worth and everything is there.

An individual approach when taking a DZ (not on a formal basis) - depending on your academic performance, teachers may complicate your task or ask you to do it using more advanced technologies.

What is very cool - 24/7 support in slack!

Awesome webinars on which debriefing takes place and not only - I reviewed some of them several times, because the material is very important and very well explained.

But the most significant thing for me was that the courses immerse me in a completely different state - the state of constant comprehension of something new, the desire for knowledge - and this is most important - it's like a motor that was started in me and now I move thanks to it. Thank you so much to the teachers for giving me a new life filled with the desire for knowledge, disappointment from what does not work, and joy from what I fixed.

The course is just amazing! A clear explanation of the material, regardless of its complexity. Many thanks to the teachers! They quickly answer questions and give reasonable and specific feedback on the tasks performed. The result speaks for itself: 5 months, and I successfully passed the interview. Excellent course! Worth it to pass!

Ruby on Rails developer, Taganrog, github

Shocking course. Intense, not boring, to the point. Excellent teachers. I didn't find any cons at all. They are treated humanely. I came in as a complete newbie. Now I'm a super newbie! I wrote a ruby ​​program (more than one), wrote a rails application (more than one), set up a server, deployed an application, attached various functionality to the application, figured out domains, ssl certificates, dns, authorizations and much more. I'm rushing into battle, I take on an independent project. In general, thank you very much, Good Programmers!

Ruby on Rails developer, Moscow, github

In principle, I was not going to take courses, but the way these guys present the material causes a great desire to work with them, learn, and just communicate.

The key advantage of the course is the fact that the guys really love and want to teach people. The course is NOT of the format "Well, we gave you the material there, and then figure it out yourself," people put their heart and soul into it and worry about how you perceived the material. After completing this course, you can safely go to work as a Rails developer.

Ruby on Rails developer, Krasnodar, github

The main points used in the development of a web application are explained in an accessible way. The most popular gems in rails are also considered.

They check homework well and make detailed comments. I appreciate the fact that the guys don’t give up on you after the end of the course and keep in touch, help in word and deed)) The site is not very convenient in terms of finding information, especially when you finish all 71 lessons, but I think the guys will finalize the rest, there’s nothing to complain about.

Team Lead at AirBnB, San Francisco

I have significant experience in online learning- this is the best online course of those that I have ever met. Everything has been worked out - high-quality material, excellent presentation. And most importantly, after the course you can really become a programmer!

I live in Silicon Valley, go to various meetups and workshops, meet graduates of the vaunted local bootcamps (the cost of which, by the way, is from 12 thousand dollars for 4 months) and I understand that my knowledge after the course is many times greater than many graduates of these famous bootcamps of Silicon valley, despite the fact that I started from scratch and never opened the terminal until “Good Programmer”))

I will wait for a work permit and I will definitely get a job. After the course, I feel the strength in myself for this, I know that it is possible! Thank you guys!

In my opinion, the guys have created a chic course that is suitable for both completely novice programmers and those who already have experience working with other languages ​​and libraries.

Excellent material and presentation, attitude in general, and the atmosphere at the webinars. The guys work hard to help each student, chewing to the smallest detail if necessary. After the course, you feel confident in your abilities, you understand that it is quite possible to get a job in the IT field, if there is a desire.

Perfectly given the foundations for a basic understanding of programming. Interesting and real tasks are given, the solution of which will help and be useful in the future.

I summarize. I think this course one of the best, and I definitely recommend it to anyone who decides to devote their lives to the field of programming. At the moment, in an active job search, the demand is quite large, therefore, everything is in your hands! Thank you guys so much and I wish you the best in the future!

Ruby on Rails developer

The course helped, I learned how to program in Ruby and on rails, I'm not a super-cool programmer, but I know that I can write anything, I may need to read something extra.

The goal was to “learn how to program and find a job.” The task was completed 100%, I learned to program, they took a job.