我需要存储由不同数据类型组成的用户输入。我需要将它们以特定格式存储在数组中。例如,如果用户输入 hai 1994 在文本框中,数据 hai 1994 应该存储在一个数组中 arr = [' hai',1994]
到目前为止:
home_controller.rb:
class HomeController < ApplicationController
def index
@data = params[:text1]
end
end
index.html.erb:
<form action = "/home/index" >
Please enter some data
<br>
<textarea name="text1" cols="40" rows="5"></textarea>
<br>
<br>
<input type="submit"/>
</form>
答案 0 :(得分:0)
您可以解析它以获取各种部分,然后迭代它。我假设你只处理字符串和整数:
def index
@data1 = params[:text1].split(" ").map do |entry|
if entry.to_i == 0 && entry != "0" # this is a string so leave it
entry
else
entry.to_i
end
end
end
这会引起你对&#34; HAI 1994&#34;并返回数组["HAI", 1994]
。
答案 1 :(得分:0)
这是您的问题的解决方案
程序: -
class Program
def method(a)
b = []
for i in 0..a-1
puts "enter a value"
b << gets.chomp.split(' ') # split the given string when it find a space between them
end
for j in 0..a-1
print "#{b} "
end
end
end
obj = Program.new
puts "how many values you want to enter "
k = gets.chomp
obj.method(k.to_i)
输出:
how many values you want to enter
1
enter a value
1991 madhu
[["1991", "madhu"]]