Store类初始化变量到数组然后遍历它.. [ruby]

时间:2016-10-06 16:48:16

标签: arrays ruby

我希望能够将变量存储到数组中,然后遍历它们,然后将结果存储在数组中并返回该新数组。

代码应该解释我想要做得更好的事情:

这是我的尝试:

# Important initializations
url_check_array = Array.new
return_array = Array.new

# The following initializes classes which then does the check by using the two variables that's passed to it
check_overall = CheckString.new("#{gitlab_cache}", 'success')
check_cache = CheckString.new("#{gitlab_cache}", 'success')
check_database = CheckString.new("#{gitlab_database}", 'success')
check_migrations = CheckString.new("#{gitlab_migrations}", 'success')

unless @is_verbose == "true"
  # I haven't done much here as I am not done yet (still trying to get things work on the 'else' part)
  url_check_array.insert(check_overall)
  puts "url_check_array = #{check_overall}" # DEBUG
  puts "Gitlab OVERALL URL is: #{gitlab_overall}" # DEBUG
else
  # url_check_array.insert("#{check_cache}", "#{check_database}", "#{check_migrations}") # Results in TypeError - no implicit conversion of String into Integer
  url_check_array.insert(check_cache, check_database, check_migrations)
  url_check_array.each do |check_item|
    return_array.insert(check_item)
  end
  #puts "Result is: #{check_cache.class}" # DEBUG
  return return_array
end

我无法弄清楚我做错了什么,因为上面的代码会导致错误。

编辑:所以问题是..如何成功地将这些类初始化放在一个数组中,然后正确地循环它们然后将结果放在另一个数组中?

EDIT2 :现在我收到以下错误:

TypeError - no implicit conversion of CheckString into Integer

EDIT3 :所以,我可以通过将url_check_array.insert更改为url_check_array.push来将这些添加到数组中...但是,我现在的问题是我的循环除了将同样的东西放入return_array(以下)之外没有做太多的事情:

[#<CheckString:0x007ff51e0b5278 @uri_str="https://git.company.com/health_check.json?token=eeMGuv", @pattern="success">, #<CheckString:0x007ff51e0b51b0 @uri_str="https://git.company.com/health_check.json?token=eeMGuv", @pattern="success">, #<CheckString:0x007ff51e0b5110 @uri_str="https://git.company.com/health_check.json?token=eeMGuv", @pattern="success">]

而不是实际结果..所以,我真正希望它做的是实际执行CheckString.new("#{gitlab_migrations}", 'success')然后将结果放入数组中。

1 个答案:

答案 0 :(得分:1)

您将类自己放在结果数组中。 你的目的是将结果本身放在那个数组中吗?

所以在你的班级CheckString中你应该有一个方法&#39;检查&#39;或类似的结果。然后在你的映射中你应该调用thatr check方法。

url_check_array.each do |check_item|
  return_array.insert(check_item.check)
end

class CheckString
  def check
    # do some checking and return something that indicates a succesful check or not, eg
    @gitlab_migrations == 'success'
  end
end