如何将数组中的随机字符串传递给视图?

时间:2014-10-02 15:39:53

标签: ruby-on-rails ruby arrays string

在我的控制器中,我定义了一系列位置,并使用sample来捕获其中一个随机字符串:

class IndexController < ApplicationController
  def index
    @location = ["England", "Scotland", "Wales", "Ireland"]
    random_location = @location.sample
  end
end

但是,我不知道在浏览器中显示一个国家/地区所需的代码。

1 个答案:

答案 0 :(得分:1)

使用Array#sample

class IndexController < ApplicationController
  def index
    # @location i_var will be available automatically inside the corresponding
    # view of this action to the Index controller.
    @location = ["England", "Scotland", "Wales", "Ireland"]
  end
end

现在在视图中 - index.html.erb

Country is <%= @location.sample %>