A Ruby egy gyönyörű programozási nyelv.
A Ruby hivatalos weblapja szerint a Ruby egy:
„ Dinamikus, nyílt forráskódú programozási nyelv, amelynek középpontjában az egyszerűség és a termelékenység áll. Elegáns szintaxisa van, amelyet természetes módon el lehet olvasni és könnyen lehet írni. ”A Ruby-t Yukihiro Matsumoto japán szoftvermérnök készítette. 2011 óta a Ruby fő tervezője és szoftvermérnöke a Heroku-nál.
Matsumoto gyakran mondta, hogy megpróbálja Rubyt természetesvé tenni, nem pedig egyszerűvé , az életet tükröző módon.
„A rubin megjelenése egyszerű, de belül nagyon összetett, akárcsak az emberi testünk” - Yukihiro MatsumotoUgyanígy érzek Ruby iránt. Ez egy összetett, de nagyon természetes programozási nyelv, gyönyörű és intuitív szintaxissal.
Intuitívabb és gyorsabb kóddal jobb szoftvereket tudunk felépíteni. Ebben a bejegyzésben megmutatom, hogyan fejezem ki gondolataimat (más néven kód) Ruby-val, kódrészletek használatával.
Gondolataim kifejezése tömb módszerekkel
Térkép
Használja a térkép módszert, hogy egyszerűsítse a kódot, és megkapja, amit akar.
A módszer térkép visszatér egy új tömböt az eredménnyel fut egy blokk után minden eleme enum.
Próbáljuk ki:
an_array.map element * element
Egyszerű a dolog.
De amikor elkezdi a Ruby-val történő kódolást, könnyű mindig használni az egyes iterátorokat.
Az egyes iterátorok az alábbiak szerint
user_ids = [] users.each user
Egyszerűsíteni lehet térkép egyetlen gyönyörű kódsort:
user_ids = users.map user.id
Vagy még jobb (és gyorsabb):
user_ids = users.map(&:id)
Válassza a lehetőséget
És amikor hozzászokott a térképhez kódoláshoz , néha a kódja ilyen lehet:
even_numbers = [1, 2, 3, 4, 5].map element # [ni, 2, nil, 4, nil] even_numbers = even_numbers.compact # [2, 4]
A térkép segítségével csak a páros számok kijelölésére anulla tárgy is. Használja a kompakt módszerrel eltávolítani az összes nulla tárgyakat.
És ta-da, kiválasztottad az összes páros számot.
Küldetés teljesítve.
Gyerünk, ennél jobbat is tehetünk! Számolt modulról hallott a select metódusról?
[1, 2, 3, 4, 5].select
Csak egy sor. Egyszerű kód. Könnyen érthető.
Bónusz
[1, 2, 3, 4, 5].select(&:even?)
Minta
Képzelje el, hogy egy tömbből véletlenszerű elemet kell kapnia. Most kezdted el tanulni a Rubyt, így az első gondolatod a következő lesz: "Használjuk a véletlenszerű módszert", és ez történik:
[1, 2, 3][rand(3)]
Nos, megértjük a kódot, de nem vagyok benne biztos, hogy elég jó-e. És mi van, ha a shuffle módszert alkalmazzuk?
[1, 2, 3].shuffle.first
Hmm. Én valójában inkább a shuffle- t használom a rand helyett . De amikor felfedeztem a minta módszert, sokkal értelmesebb volt:
[1, 2, 3].sample
Nagyon, nagyon egyszerű.
Nagyon természetes és intuitív. Kérünk egy mintát egy tömbből, és a metódus visszaadja. Most boldog vagyok.
Mi van veled?
Ruby szintaxissal fejezem ki gondolataimat
Mint már korábban említettem, imádom, ahogy Ruby hagy kódolni. Számomra ez igazán természetes. Megmutatom a gyönyörű Ruby szintaxis egyes részeit.
Implicit megtérülés
A Ruby bármelyik állítása visszaadja az utoljára kiértékelt kifejezés értékét. Egyszerű példa a getter módszer. Hívunk egy módszert, és várunk némi értéket cserébe.
Lássuk:
def get_user_ids(users) return users.map(&:id) end
De mint tudjuk, Ruby mindig az utolsó értékelt kifejezést adja vissza. Miért használja a return utasítást?
Miután 3 évig használtam a Ruby-t, nagyszerűen érzem magam szinte minden módszer alkalmazásával a visszatérési nyilatkozat nélkül .
def get_user_ids(users) users.map(&:id) end
Több feladat
Ruby lehetővé teszi, hogy egyszerre több változót rendeljek hozzá. Amikor elkezdi, lehet, hogy így kódol:
def values [1, 2, 3] end one = values[0] two = values[1] three = values[2]
De miért ne rendelne egyszerre több változót?
def values [1, 2, 3] end one, two, three = values
Eléggé megdöbbentő.
Kérdéseket feltevő módszerek (más néven predikátumok)
One feature that caught my attention when I was learning Ruby was the question mark (?) method, also called the predicates methods. It was weird to see at first, but now it makes so much sense. You can write code like this:
movie.awesome # => true
Ok… nothing wrong with that. But let’s use the question mark:
movie.awesome? # => true
This code is much more expressive, and I expect the method’s answer to return either a true or false value.
A method that I commonly use is any? It’s like asking an array if it has anything inside it.
[].any? # => false [1, 2, 3].any? # => true
Interpolation
For me string interpolation is more intuitive than string concatenation. Period. Let’s see it in action.
An example of a string concatenation:
programming_language = "Ruby" programming_language + " is a beautiful programming_language" # => "Ruby is a beautiful programming_language"
An example of a string interpolation:
programming_language = "Ruby" "#{programming_language} is a beautiful programming_language" # => "Ruby is a beautiful programming_language"
I prefer string interpolation.
What do you think?
The if statement
I like to use the if statement:
def hey_ho? true end puts "let’s go" if hey_ho?
Pretty nice to code like that.
Feels really natural.
The try method (with Rails mode on)
The try method invokes the method identified by the symbol, passing it any arguments and/or the block specified. This is similar to Ruby’s Object#send. Unlike that method, nil will be returned if the receiving object is a nil object or NilClass.
Using if and unless condition statement:
user.id unless user.nil?
Using the try method:
user.try(:id)
Since Ruby 2.3, we can use Ruby’s safe navigation operator (&.) instead of Rails try method.
user&.id
Double pipe equals (||=) / memoization
This feature is so C-O-O-L. It’s like caching a value in a variable.
some_variable ||= 10 puts some_variable # => 10 some_variable ||= 99 puts some_variable # => 10
You don’t need to use the if statement ever. Just use double pipe equals (||=) and it’s done.
Simple and easy.
Class static method
One way I like to write Ruby classes is to define a static method (class method).
GetSearchResult.call(params)
Simple. Beautiful. Intuitive.
What happens in the background?
class GetSearchResult def self.call(params) new(params).call end def initialize(params) @params = params end def call # ... your code here ... end end
The self.call method initializes an instance, and this object calls the call method. Interactor design pattern uses it.
Getters and setters
For the same GetSearchResult class, if we want to use the params, we can use the @params
class GetSearchResult def self.call(params) new(params).call end def initialize(params) @params = params end def call # ... your code here ... @params # do something with @params end end
We define a setter and getter:
class GetSearchResult def self.call(params) new(params).call end def initialize(params) @params = params end def call # ... your code here ... params # do something with params method here end private def params @params end def params=(parameters) @params = parameters end end
Or we can define attr_reader, attr_writer, or attr_accessor
class GetSearchResult attr_reader :param def self.call(params) new(params).call end def initialize(params) @params = params end def call # ... your code here ... params # do something with params method here end end
Nice.
We don’t need to define the getter and setter methods. The code just became simpler, just what we want.
Tap
Imagine you want to define a create_user method. This method will instantiate, set the parameters, and save and return the user.
Let’s do it.
def create_user(params) user = User.new user.id = params[:id] user.name = params[:name] user.email = params[:email] # ... user.save user end
Simple. Nothing wrong here.
So now let’s implement it with the tap method
def create_user(params) User.new.tap do |user| user.id = params[:id] user.name = params[:name] user.email = params[:email] # ... user.save end end
You just need to worry about the user parameters, and the tap method will return the user object for you.
That’s it
We learned I write idiomatic Ruby by coding with
- array methods
- syntax
We also learned how Ruby is beautiful and intuitive, and runs even faster.
And that’s it, guys! I will be updating and including more details to my blog. The idea is to share great content, and the community helps to improve this post! ☺
I hope you guys appreciate the content and learned how to program beautiful code (and better software).
If you want a complete Ruby course, learn real-world coding skills and build projects, try One Month Ruby Bootcamp. See you there ☺
This post appeared first here on my Renaissance Developer publication.
Have fun, keep learning, and always keep coding!
My Twitter & Github. ☺