The Ruby language has many special functions that deserve further research. For example, the syntax is different from that of other programming languages. Here we will understand some concepts related to Ruby's special syntax.
- Basic Syntax of common Ruby Libraries
- Using pp () to output two-dimensional arrays in Ruby
- Ruby on Rails directory files
- Ruby function pointer concepts
- Ruby Rmagick Installation Guide
The question is looking for change. Suppose we need to find another person with a change of 39 USD,
The result will be (dollar coins include, 10, 5, and 1 ):
To solve this problem with the special Ruby syntax, you only need two lines,
- Def make_change (amount,
Coins = [])
- Coins. sort! {| X, y | y <=> x}
- Return coins. map! {| Coin |
- F = amount/coin; amount
% = Coin; Array. new (f) {coin}
}. Flatten
- End
- P make_change (39, [10, 1, 5, 25])
The greedy algorithm is used here. The biggest coin is used to divide each time, and the remaining money is used for the same calculation with the next coin.
A special Ruby syntax is the most flexible and agile language I have ever seen.