需要帮助将 Ruby 代码分解为方法
我正在编写一个程序是为了更好地学习编程,我希望使用 RSpec,这样我也可以学习它。然而,事实上,该代码对 RSpec 并不是特别友好,因此我需要将其分解为方法,以便我可以对其进行测试。
我不需要任何人为我编写代码,但也许可以解释我如何分解它。我是编程新手,这种事情(将事物分解为方法)对我来说是一个非常困难的概念。
这就是我所拥有的:
if params[:url] != ''
url = params[:url] #line created so I can return url more easily (or, in general)
words = params[:word].gsub("\n", ",").delete("\r").split(",") #.delete redundant?
words.reject!(&:empty?)
words.each(&:lstrip!)
return "#{words}", "#{url}" #so that I can return url, not sure how to do that yet
end
该代码是一个 SERP 检查器,它需要一个 url 和关键字并检查它们在搜索引擎中的位置。
对于 url,它只是用户希望检查的网站的 url...对于 word,这将是他们希望在 Google 中检查其网站的关键字。用户可以像这样填写输入表单:
Corn on the cob,
Fibonacci,
StackOverflow
Chat, Meta, About
Badges
Tags,,
Unanswered
Ask Question
I am writing a program to better learn to program and I wish to use RSpec so that I can learn that as well. However, as is, the code isn't particularly RSpec friendly, so I need to break it up into methods so that I can test it.
I don't need anyone to write the code for me, but perhaps explain how I can break it up. I am new to programming and this kind of thing (breaking things up into methods) is a really difficult concept for me.
Here's what I have:
if params[:url] != ''
url = params[:url] #line created so I can return url more easily (or, in general)
words = params[:word].gsub("\n", ",").delete("\r").split(",") #.delete redundant?
words.reject!(&:empty?)
words.each(&:lstrip!)
return "#{words}", "#{url}" #so that I can return url, not sure how to do that yet
end
The code is a SERP checker, it takes a url and keywords and checks their location in the search engines.
For url, it'll just be the url of the website the user wishes to check... for word, it would be the keywords they wish to check their site against in Google.. a user may fill out the input form like so:
Corn on the cob,
Fibonacci,
StackOverflow
Chat, Meta, About
Badges
Tags,,
Unanswered
Ask Question
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码采用一个杂乱的字符串并将其转换为一个干净的数组。首先清理字符串,然后抛光数组。您可以为这些操作定义方法。
Your code takes a sloppy string and turns it into a clean array. You first clean up the string, then you polish the array. You could define methods for these actions.
url = params[:url]
。如果您打算这样做,则应该在引用相同内容的其他地方之前执行此操作,以减少对param
调用[]
的数量。scan(/[^\s\r,]+/)
。url = params[:url]
. If you are going to do that, you should do it before other places where you refer to the same thing to reduce the amount of calling[]
onparam
.scan(/[^\s\r,]+/)
.