如何结束真正的“循环”防御?

时间:2018-07-26 15:33:29

标签: ruby

我正在使用红宝石

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

    let orderedTabBarItemViews: [UIView] = {
        let interactionViews = tabBar.subviews.filter({ $0 is UIControl })
        return interactionViews.sorted(by: { $0.frame.minX < $1.frame.minX })
    }()

    guard
        let index = tabBar.items?.index(of: item),
        let subview = orderedTabBarItemViews[index]?.subviews.first
    else {
        return
    }

    performSpringAnimation(for: subview)
}

func performSpringAnimation(for view: UIView) {
    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
        view.transform = CGAffineTransform(scaleX: 1.25, y: 1.25)
        UIView.animate(withDuration: 0.5, delay: 0.2, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseInOut, animations: {
            view.transform = CGAffineTransform(scaleX: 1, y: 1)
        }, completion: nil)
    }, completion: nil)
}

我在问如何结束“循环”。 (真的不是)。因为程序在我回答y之后一直重复(是的,所以信息是正确的。)。

我在使用代码之前和之后都有一些编码。

1 个答案:

答案 0 :(得分:1)

又是我。使用条件语句来实现此目的。

puts "Age: "
input_age = gets.chomp
begin
  age = Integer(input_age)
  if age > 0 and age <= 130 then 

    puts ""
    puts "You are #{input_age} yo."

  else
    puts "Put a valid age please."
  end
end

如果您要一直询问直到用户输入有效年龄,就可以尝试使用递归函数 感谢@dutow的教育,请不要在此处使用递归。使用循环:

def getAge()
  finished = false
  puts "Age: "
  input_age = gets.chomp

  until finished do
    age = Integer(input_age)
    if age > 0 and age <= 130 then 

      puts ""
      puts "You are #{input_age} yo."

      finished = true

    else
      puts "Put a valid age please."

    end
  end
  input_age
end

getAge()

大量修改:

在您整个程序的范围内,这是一个可行的解决方案:

def getName(prompt_text)
  finished = false
  result = ""

  until finished do
    puts prompt_text
    result = gets.chomp

    puts "You entered: #{result}. Is this correct? [y/n]"
    response = gets.chomp
    if response == "y"
      finished = true
    end
  end
  return result
end

def getAge()
  finished = false
  puts "Age: "
  input_age = gets.chomp

  until finished do
    age = Integer(input_age)
    if age > 0 and age <= 130 then 

      puts ""
      puts "You are #{input_age} yo."

      finished = true

    else
      puts "Put a valid age please."

    end
  end
  input_age
end



puts "ENTERING STAGE~1"
puts ""
first_name = getName("First Name: ")
puts 
last_name = getName("Last Name: ")
puts
input_age = getAge()
puts
puts "You are #{first_name} #{last_name}. You have been living for #{input_age} years now."

问题中的代码被荒谬地破坏了。您正在进行许多不同的事情,但是故事的寓意是:使用函数。经常使用它们。它们真的很有用。感谢this question上的@Jack Bracken提供了一些更新的代码。