官术网_书友最值得收藏!

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:

  1. Split the string into words.
  2. Reverse the order of the words.
  3. 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.

主站蜘蛛池模板: 凤庆县| 宁都县| 兴国县| 南丰县| 乌审旗| 砚山县| 苍山县| 东至县| 长白| 苏尼特左旗| 安庆市| 克什克腾旗| 怀来县| 抚顺县| 北海市| 大姚县| 祁东县| 延庆县| 鹤壁市| 聂拉木县| 涟源市| 嘉峪关市| 英德市| 和平区| 进贤县| 鸡泽县| 雷州市| 和林格尔县| 万宁市| 舒兰市| 蒙城县| 亚东县| 阿拉善盟| 上栗县| 五台县| 青田县| 姚安县| 贡觉县| 阿图什市| 彭水| 新晃|