红宝石循环和班;再次将字符串分割为一个数组,并返回一个字符串 [英] Ruby loops and classes; splitting a string into an array and back to a string again
问题描述
红宝石新手在这里与类循环工作。我本来是创造,将采取一个字符串,并添加惊叹号每个单词的结尾(通过将其与.split数组),并加入一个方法再次惊呼字作为一个字符串。我已经在这两个小时已经和决定我应该寻求帮助。我有想法了一把,但我一直想出一个NoMethod错误。下面是那对我有意义,但当然,这是行不通的途径之一。我也在最后补充规格。
类StringModifier
attr_accessor中:字符串
高清初始化(字符串)
@string =字符串
结束 DEF宣布
new_array = []
string.split.each做|字|
新数组=#{}字!
new_array.join
结束
new_array
结束
结束
SPECS
描述StringModifier做
形容#proclaim吗
它每一个字后面加上一个感叹号吗
blitzkrieg_bop = StringModifier.new(嘿嗬走吧)。宣布
期待(blitzkrieg_bop)。为了EQ(嘿!嗬!我们走!!)
结束
结束
结束
写您的方法:
宣布高清
string.split.map {|字| #{字}! }。加入()
结束
还是把它写为:
宣布高清
A = string.split
(%S!* a.size%一).strip
结束
测试:
[30]撬(主)GT; A =嘿嗬走吧.split
= GT; [嘿我们走吧]
[31]撬(主)GT; (%S!* a.size%一).strip
= GT; 嘿我们走吧!
[32]撬(主)GT;
Ruby newbie here working on loops with classes. I was supposed create a method that would take a string and add exclamation points to the end of each word (by making it an array with .split) and join the 'exclaimed' words as a string again. I've been at this for two hours already and decided I should seek help. I have a handful of ideas but I keep coming up with a NoMethod error. Below is one of ways that made sense to me but of course, it doesn't work. I've also added specs at the very end.
class StringModifier
attr_accessor :string
def initialize(string)
@string = string
end
def proclaim
new_array = []
string.split.each do |word|
new array = "#{word}!"
new_array.join
end
new_array
end
end
SPECS
describe StringModifier do
describe "#proclaim" do
it "adds an exclamation mark after each word" do
blitzkrieg_bop = StringModifier.new("Hey ho let's go").proclaim
expect(blitzkrieg_bop).to eq("Hey! ho! let's! go!")
end
end
end
Write your method as:
def proclaim
string.split.map { |word| "#{word}!" }.join(" ")
end
Or write it as :
def proclaim
a = string.split
("%s! " * a.size % a).strip
end
Tested :
[30] pry(main)> a = "Hey ho let's go".split
=> ["Hey", "ho", "let's", "go"]
[31] pry(main)> ("%s! " * a.size % a).strip
=> "Hey! ho! let's! go!"
[32] pry(main)>
这篇关于红宝石循环和班;再次将字符串分割为一个数组,并返回一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!