- Comprehensive Ruby Programming
- Jordan Hudgens
- 254字
- 2021-07-02 21:13:28
Using the join method
We've walked through the split method, which allows you to convert a string into a collection of characters. Thankfully, Ruby also has a method that does the opposite, which is to allow you to convert an array of characters into a single string, and that method is called join. Let's imagine a situation where we're asked to reverse the words in a string. This is a common Ruby coding interview question, so it's an important concept to understand, since it tests your knowledge of how string works in Ruby. Let's imagine that we have a string, such as this:
str = "backwards am I"
If we're asked to reverse the words in the string, the pseudocode for the algorithm would be as follows:
- Split the string into words.
- Reverse the order of the words.
- Merge all of the split words back into a single string.
We can actually accomplish each of these requirements in a single line of Ruby code. The following code snippet will perform the task:
str.split.reverse.join(' ')
This code will convert the single string into an array of strings, for the example, it will equal ["backwards", "am", "I"]. From there, it will reverse the order of the array elements, so the array will equal ["I", "am", "backwards"]. With the words reversed, now we simply need to merge the words into a single string, which is where the join method comes in. Running the join method will convert all of the words in the array into one string.
- 演進(jìn)式架構(gòu)(原書(shū)第2版)
- Learning Neo4j
- Learning NServiceBus(Second Edition)
- What's New in TensorFlow 2.0
- Redis Applied Design Patterns
- Mastering Yii
- Visual C#通用范例開(kāi)發(fā)金典
- NoSQL數(shù)據(jù)庫(kù)原理
- Tableau 10 Bootcamp
- Node.js:來(lái)一打 C++ 擴(kuò)展
- 智能手機(jī)APP UI設(shè)計(jì)與應(yīng)用任務(wù)教程
- Buildbox 2.x Game Development
- Clojure for Java Developers
- Python Social Media Analytics
- C/C++代碼調(diào)試的藝術(shù)(第2版)