Picking up Ruby Fast, as a Python Dev pt II
Vicki Langer
Posted on November 17, 2020
This is a continuation of Picking up Ruby Fast, as a Python Dev. Again, expect examples with no math and no crappy names
Some Reflection
I really never thought I'd pick up a second language, but now that I am it's a lot easier than expected. Now, don't take that like I said it's easy. It's just not quite as hard and confusing as it was when I had no clue how to code.
Vicki Langer@vicki_langerLearning a second language is very different from learning your first. When learning your first, you have no baseline or frame of reference to compare to.
Learning a second language just takes figuring out punctuation, vernacular, and constant translating from what you do know.03:49 AM - 17 Nov 2020
More differences
Classes, Functions, and Methods, oh my
Turns out, Python isn't a true OOP language as it still has functions. Ruby, on the other hand, is a true OOP language and does not call functions. Instead, messages are sent to methods of an instance of an object
we don't call functions, we send messages to methods on an instance of a given object in Ruby!
Iterating
Both Python and Ruby have loops, but the syntax is different. Here's a comparison of the same code in each language
In Python
# python
# throw each toy some number of times for some dog
def throw_toy(amount, name = "the dog")
toy_list = ["ball", "frisbee", "rock", "another ball", "cat"]
for toy in toy_list:
print(f"threw {toy} {amount} times for {name.capitalize()}"
throw_toy(3, "Cheeto")
throw_toy(1, "wiley")
Here it is in Ruby
#ruby
# throw each toy some number of times for some dog
def throw_toy(amount, name = "the dog")
toy_list = ["ball", "frisbee", "rock", "another ball", "cat"]
toy_list.each{
|toy| puts "threw #{toy} #{amount} times for #{name.capitalize}"
}
end
throw_toy 3, "Cheeto"
throw_toy 1, "wiley"
Parentheses in Ruby
Turns out, parentheses are optional but preferred in some cases.
If you only have one arg, parentheses probably aren't needed. More than one arg and it's a good idea to have them.
# this is acceptable
def throw_toy amount, name = "the dog"
# this is preferred because there is >1 argument
def throw_toy(amount, name = "the dog")
A Few More Quick Points of Difference
Ruby | Python |
---|---|
BasicObject & Object are inherited by literally everything |
has concept of both methods & functions where methods belong to a class |
methods | functions |
494595.to_s |
string(494595) |
If you missed the first post, I've heard it's a good read and there's cats.
Posted on November 17, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.