Idiomatic Process Model
Ruby is a beautiful programming language.
Ruby is a beautiful programming language.
According to the official Ruby page, Ruby is:
According to the official Ruby page, Ruby is:
„dynamic open source programming language with a focus on simplicity and productivity. It has elegant syntax that is natural to read and easy to write.”
"A dynamic open source programming language focused on simplicity and productivity. It has elegant syntax, is easy to read and easy to write."
Ruby was developed by Yukihiro Matsumoto, a Japanese software developer. He has been the lead designer and software engineer for Ruby at Heroku since 2011.
Ruby was developed by Japanese software developer Yukihiro Matsumoto. He has been the lead designer and software engineer for Heroku Ruby since 2011.
Matsumoto always said he was tryingto make Ruby natural, not easy, in a way that reflects life.
Matsumoto always said he triedProMake Ruby natural, but not easyin a way that reflected life.
"Ruby is simple on the outside but very complex on the inside, just like our human body" - Yukihiro Matsumoto
"Ruby is simple on the outside but very complex on the inside, just like our human body" - Yukihiro Matsumoto
I feel the same way about Ruby. It's a complex but very natural programming language with a nice and intuitive syntax.
I feel the same way about Ruby. It's a complex but very natural programming language with a nice and intuitive syntax.
With more intuitive and faster code, we can build better software. In this post, I'll show you how I express my thoughts (aka code) with Ruby using code snippets.
With more intuitive and faster code, we can build better software. In this article, I'll show you how to use Ruby to express your ideas (aka code) through code snippets.
Express my thoughts using array methods
Map
Use oMapMethod to simplify your code and get what you want.
Use oMapMethod to simplify your code and get what you want.
The methodMapreturns a new array containing the results of executing a block once for each item in the enumeration.
The methodMapreturns a new array and executes the block once for each element in the enumeration.
We will try:
Let us try it:
an_array.map { |element| element * element }
So easy.
As simple as that.
But once you start programming with Ruby, it's easy to get theeveryoneIterator.
But once you start programming in Ruby, it's easy to use every time.everyoneIterator.
ÖeveryoneIterator as shown below
Everyoneiterator is shown in the figure below
user_ids = []users.each { |Benutzer| user_ids << user.id }
It can be simplified withMapin one nice line of code:
The simplification can be done in a nice line of code viaMap:
user_ids = users.map { |User| Benutzer ID }
Or even better (and faster):
or even better (faster):
user_ids = Benutzer . map(&:id)
Select
And if you are used to coding withMap, sometimes your code looks like this:
If you are used to coding withcards, sometimes your code looks like this:
even numbers = [1, 2, 3, 4, 5].map { |element| element is element.even? } #[ni, 2, zero, 4, zero]pairs_numbers = pairs_numbers. compact #[2, 4]
UseMapSelecting only the even numbers will return thenothingobject too. Use thecompactmethod to remove allnothingobjects.
Select only even numbers with aMaporReturnsno objects either. Use thecompactmethod to remove allnothingobjects.
And ta-da, you picked all the even numbers.
Ta-da, you picked all the even numbers.
Mission accomplished.
Job Complete.
Come on, we can do better! Have you heard of theSelectenumerable module method?
Come on, we can do better!Have you heard about the selectionMethod not module enumerable ?
[1, 2, 3, 4, 5]. choose { |item| element.same? }
Just one line. Simple code. Easy to understand.
Just one line. Simple code. easy to understand.
Bonus___
[1, 2, 3, 4, 5]. select(&:equal?)
sample
Imagine you need to retrieve a random element from an array. You've just started learning Ruby, so your first thought will be, “Let's use itCoincidentallymethod" and this happens:
Imagine you need to retrieve a random element from an array. You've just started learning Ruby, so your first thought is, "Let's use itCoincidentallymethod", and this is how it works:
[1, 2, 3][rand(3)]
Well we can understand the code but I'm not sure if it's good enough. And if we use themMixMethod?
Well we can understand the code but I'm not sure if it's good enough. And if we use themMixMethod?
[1, 2, 3].shuffle.first
hmm Actually I prefer to useMixanRand. But when I found themsamplemethod, it made a lot more sense:
Well actually I prefer to use itMixRand. But it made more sense when I found thoseexample method:
[1, 2, 3]. sample
Very, very easy.
It's very, very simple.
Totally natural and intuitive. We asked for onesampleof an array and the method returns it. Now I am happy.
Very natural and intuitive. we ordered onesampleof the array and the method returns it. I am very happy now.
Is that you?
Is that you?
Express my thoughts with Ruby syntax (Express my thoughts with Ruby syntax)
As I mentioned earlier, I love the way Ruby lets me program. It's very natural for me. I'll show you bits of beautiful Ruby syntax.
As mentioned before, I like the way Ruby lets me write code. It really comes naturally to me. I'll show you some good Ruby syntax.
implicit return
Every statement in Ruby returns the value of the last expression evaluated. A simple example is theGetterMethod. We invoke a method and expect something in return.
Every statement in Ruby returns the value of the last expression evaluated. A simple example isGettermethods. We call a method and expect a value to be returned.
Let's see:
Let's see:
def get_user_ids(User)returning users. map(&:id)Film
But as we know, Ruby always returns the last expression evaluated. Why use theReturnsExplanation?
However, Ruby is known for always returning the most recently evaluated expression. Why use theReturnsExplanation?
After using Ruby for 3 years, I feel great using almost any method without itReturnsExplanation.
After using Ruby for three years, I can use almost any method without itReturnsExplanation.
def get_user_ids(User)Benutzer. map(&:id)Film
multiple tasks
Ruby allows me to assign multiple variables at once. At first you could code like this:
Ruby allows me to assign multiple variables at once. To start you can code something like this:
def values[1, 2, 3]Filmone = values[0]two = values[1]three = values[2]
But why not assign multiple variables at once?
But why not assign multiple variables at once?
def values[1, 2, 3]Filmone, two, three = values
Unbelievable.
impressive
Methods that ask questions (also called predicates)
One feature that caught my attention when I was learning Ruby was thisQuestion mark (?)method, also calledpredicatesmethods. It was weird to see at first, but now it makes a lot of sense. You can write code like this:
One feature that caught my attention while learning Ruby wasQuestion mark (?)Methods, also known aspredicatemethods. It seemed weird at first, but now it makes perfect sense. You can write code like this:
movie.awesome # => true
Okay... nothing wrong with that. But let's use the question mark:
Ok thats right. But let's use question marks:
movie.amazing? # => true
This code is much more expressive and I expect the method response to return arealorNOT CORRECTBravery.
This code is more expressive, I want the method response to be returnedrealorNOT CORRECTBravery.
A method I use often isnone?It's like asking an array if it issomeDing drin.
What is my usual method?It's like asking if there is onenothinginside the matrix.
[].none? # => wrong[1, 2, 3]. none? # => true
Interpolation
To me, string interpolation is more intuitive than string concatenation. Over time. Let's see it in action.
To me, string interpolation is more intuitive than string concatenation. Wait. Let's see what he does.
An example of string concatenation:
String concatenation example:
Programming_language = "Rubin"Programming_language + "it's a beautiful programming language" # => "Ruby is a beautiful programming language"
An example of string interpolation:
String interpolation example:
Programming_language = "Rubin""#{programming_language} is a beautiful programming language" # => "Ruby is a beautiful programming language"
I prefer string interpolation.
I prefer string interpolation.
What do you think?
What do you think?
if statement (the if statement)
I like to use thoseWhat ifExplanation:
I like to useWhat ifAffirmations:
def hey_ho?realFilmLocation "Let's go" se hey_ho?
Very nice to code like that.
This code is really good.
It looks very natural.
It looks very natural.
The try Method (with Rails mode enabled)
Öexperimentmethod invokes the method identified by the symbol and passes it any arguments and/or the specified block. This is similar to Rubyobject#send.Unlike this methodnothingis returned if the receiving object is anothingobject orNile Class.
the attemptmethod invokes the method identified by the symbol and passes it any arguments and/or the specified block. This is similar to Rubyobject#send.Unlike the method, if the received object is anothingobject orNile Class nothingWill be returned.
Useif and unlessstate statement:
Useconditionally and unlessconditional statements:
user.id unless user.nil?
Use ofexperimentMethod:
Use oexperimentMethod:
of the user. try (:id)
Since Ruby 2.3 we can use the Ruby Safe Browsing operator(&.)instead of railsexperimentMethod.
Since Ruby 2.3 we can use the Ruby Safe Browsing operator(&.)instead of railsexperimentMethod.
user identification
double pipe is equal (||=) / memoization (double pipe equal to (|| =)/ To notice)
This feature is so cool. It's like caching a value in a variable.
This feature is so cool. How to cache a value in a variable.
some_variable ||= 10set some_variable # => 10some_variable ||= 99set some_variable # => 10
You don't have to use themWhat ifstatement already. Just use equal twin tubes(||=)and done.
You don't have to useWhat ifExplanation. Just use equal twin tubes( || = )and you're good to go.
Simple and easy.
Simple and easy.
class static method
One way I like to write Ruby classes is to define astaticMethod (Class method).
One way I like to write Ruby classes is to define astaticMethod (Class method).
GetSearchResult. call (parameter)
Simple. Sweet. Intuitive.
Simple. Beauty. intuitive.
What's happening in the background?
What's happening in the background?
Class GetSearchResultdef car. call (parameter)new(params).callFilmdef initialize(Parameter)@params = ParameterFilmlast call# ... here your code ...FilmFilm
ÖAuto. call method initializes an instance and this object calls theturn onMethod.interactive design patternuse that.
the car.callmethod initializes an instance and this object calls theturn onMethod.The Interactor design patternuse that.
getters and setters
for the sameGetSearchResultClass If we want to use the parameters, we can use @params
for the sameGetSearchResultClass If you want to use parameters, you can use @params
Class GetSearchResultdef car. call (parameter)new(params).callFilmdef initialize(Parameter)@params = ParameterFilmlast call# ... here your code ...@params # do something with @paramsFilmFilm
We define astandardizereGetter:
We define astandardizereGetter:
Class GetSearchResultdef car. call (parameter)new(params).callFilmdef initialize(Parameter)@params = ParameterFilmlast call# ... here your code ...params # do something here with the params methodFilmPrivatedefinition parameters@paramsFilmdef params=(Parameter)@params = ParameterFilmFilm
or we can defineatr_reader,atr_writer,oratr_accessor
or we can defineatr_reader,atr_writeroratr_accessor
Class GetSearchResultatr_reader :paramdef car. call (parameter)new(params).callFilmdef initialize(Parameter)@params = ParameterFilmlast call# ... here your code ...params # do something here with the params methodFilmFilm
legal.
very nice
We don't have to hire themGetterestandardizermethods. The code has become simpler, just like we want.
We don't have to defineGetterestandardizermethods. The code got simpler, just like we wanted.
Beat
Imagine you want to define acreate_userMethod. This method instantiates, defines the parameters, stores, and returns the user.
Suppose you want to define acreate_userMethod. This method instantiates, defines parameters, saves and returns the user.
Let's do this.
Let's do this.
def create_user (Parameter)user = user. Newuser.id = Parameter[:id]user.name = Parameter[:Name]user.email = Parameter[:E-Mail]#...of the user. save from the userFilm
Simple. Nothing wrong here.
Simple. Yes
So now let's implement it withtouchMethod
Now let's implement it withtouchMethod
def create_user (Parameter)User.new.tap |Users|user.id = Parameter[:id]user.name = Parameter[:Name]user.email = Parameter[:E-Mail]#...of the user. save FilmFilm
You only need to worry about user parameters and thetouchThe method returns the user object for you.
You only have to worry about the user parameter, thetouchThe method returns the user object.
That's it (that's it)
We learned that I write idiomatic Ruby by coding with
We found out that I consume
- Array methods Array method
- syntax syntax
We also learned how beautiful and intuitive Ruby is and runs even faster.
We also learned how beautiful, intuitive, and faster Ruby is to run.
And that's it folks! I will update my blog and add more details. The idea is to share great content and the community will help make this post better! ☺
That's it folks! I will update my blog and add more details. The idea is to share good content and the community can help improve this information! ☺
I hope you enjoy the content and learn to write beautiful code (and better software).
I hope everyone enjoyed the content here and learned how to write beautiful code (and better software).
If you want a full Ruby course, learn hands-on programming skills, and create projects, give it a tryEinmonatiges Ruby Bootcamp. See you there ☺
If you want to take a full Ruby course, learn real programming skills, and create projects, give it a tryRuby Bootcamp for a month. i see you there
This post appeared firston hereon myRenaissance developer release.
This post originally appearedon hereon myrenaissance developer contribution.
Have fun, keep learning and keep coding!
Have fun, keep learning and keep coding!
My Twitter and Github. ☺
My Twitter and Github. ☺
Translated from: https://www.freecodecamp.org/news/idiomatic-ruby-writing-beautiful-code-6845c830c664/
Idiomatic Process Model