- 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.
- Designing Hyper-V Solutions
- EPLAN實戰(zhàn)設(shè)計
- PhoneGap:Beginner's Guide(Third Edition)
- Spring MVC+MyBatis開發(fā)從入門到項目實踐(超值版)
- Instant Zurb Foundation 4
- SSH框架企業(yè)級應(yīng)用實戰(zhàn)
- Learning Kotlin by building Android Applications
- Python物理建模初學(xué)者指南(第2版)
- 深入理解Kafka:核心設(shè)計與實踐原理
- Java EE輕量級解決方案:S2SH
- 跟小樓老師學(xué)用Axure RP 9:玩轉(zhuǎn)產(chǎn)品原型設(shè)計
- Linux Networking Cookbook
- Mastering Unity Scripting
- 精通Rust(第2版)
- 深入淺出Go語言核心編程