[Ruby]學Ruby的三大概念、二次方的新解法

Kaycheng
2 min readOct 31, 2017

--

學會Ruby要懂得三大概念:

了解變數(value)是怎麼運作的。

了解if...elsif...else...end怎麼用。

了解迴圈(for/while)的用法。

另外,在做專案時,應該先想通則(專案要達成的目標),再把特例做出來。以免專案題目有過多的特例,而浪費時間。

先前在做leetcode上的power_of_two這題,想法是先把特例(<1,=1)寫出來,然後把>1的正整數分成,能一直被二整除到最後變為1,則為true;反之,則false。

而今天看到不一的解法,只考慮2的次方數[1,2,4,8...],並且設兩個變數(target和base)

2  =  | 1 |  *  | 2 |4  =  | 2 |  *  | 2 |8  =  | 4 |  *  | 2 |
| |
target base(次方>。若題目是3的次方,則base為3)

這個解法也很有趣,以後解leetcode,可以想辦法先解出一個後,再用別的角度找另一個方法來解看看。

def power_of_two(n)  if n == 1    return true  end
target = 1 base = 2 while(true) target = target * base return true if target == n return false if target > n endend

今天發現,自己在理解Ruby語法的所需時間更短了。而且更能懂得怎麼把架構,和執行碼寫出來。這就是熟能生巧的Aha moment嗎?總之,是個令人開心的感受呢!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response