Skip to content

Commit 6aa65e6

Browse files
committed
updates
1 parent fc6fdb2 commit 6aa65e6

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

readme.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,35 @@ While Python values one main way of solving a problem, Ruby - influenced by Perl
7878

7979
With more freedom and less syntactyical rules, many Rubyists believe that Ruby is a much more elegant language - and it is. But you can also often see messy code (especially from beginners) that can be difficult for other developers to read. For example, you can put multiple statements on one line. This can look good - and be readable - depending on how it's coded or it can be a mess.
8080

81+
Let's compare some code. The following snippets of code are for solving the Fibonnoci sequence:
82+
83+
*Ruby:*
84+
85+
```ruby
86+
fib = Hash.new{ |h,k| h[k] = k < 2 ? k : h[k-1] + h[k-2] }
87+
```
88+
89+
*Python:*
90+
91+
```python
92+
def fib(n):
93+
if n < 2:
94+
return n
95+
else:
96+
return fib(n-1) + fib(n-2)
97+
```
98+
99+
Although you can write this code in many ways, both of these methods are *true* to the language. In other words, the Ruby example is very Ruby-ish while the Python example is very Python-ish. Can you read the Ruby code? It may be more elegant, since it is on one line, but it's very hard to read. Meanwhile, I can easily follow the Python code. You of course can write code anyway you want. It's adviseable to write Ruby code, when beginning, in a more Pythonic way - which simply means making it more readable:
100+
101+
```ruby
102+
def fib(n)
103+
if n <= -2
104+
(-1)**(n+1) * fib(n.abs)
105+
elsif n <= 1
106+
n.abs
107+
else
108+
fib(n-1) + fib(n-2)
109+
end
110+
end
111+
```
81112

0 commit comments

Comments
 (0)