CmsService::SearchContentPractiseProblems.form_fields.each do |field|
if field[:key].to_s === "answer_a"
row field[:key] do
content['answers']['answer_a']
end
elsif field[:key].to_s === "answer_b"
row field[:key] do
content['answers']['answer_b']
end
elsif field[:key].to_s === "answer_c"
row field[:key] do
content['answers']['answer_c']
end
elsif field[:key].to_s === "answer_d"
row field[:key] do
content['answers']['answer_d']
end
else
row field[:key] do
content[field[:key].to_s]
end
end
here i want to write the following if elsif through loops but I am stucked to get the solution can somebody help me in that
my form field is:
def self.form_fields
[
{ key: :code, label: "Code"},
{ key: :ordering, label: "Ordering"},
{ key: :content, label: "Practise Question", editable: true},
{ key: :answer_a, label: "Answer A", editable: true},
{ key: :answer_b, label: "Answer B", editable: true},
{ key: :answer_c, label: "Answer C", editable: true},
{ key: :answer_d, label: "Answer D", editable: true},
{ key: :explaination, label: "Answer Exp.", editable: true}
]
end
and the response that I want after processingg is
{
"code": "ascending-order-pq-1",
"content": "Arrange the following numbers in ascending order.\n22, 2322, 2222, 222",
"ordering": 1,
"answers": {
"answer_b": "22 < 222 < 2222 < 2322",
"answer_a": "22 < 222 < 2322 < 2222",
"answer_d": "2322 < 2222 < 222 < 22",
"answer_c": "22 < 2222 < 222 < 2322"
},
"correct": "answer_b",
"explaination": "While comparing multi-digit numbers, the numbers with the least number of digits come first. For multi-digit numbers with the same number of digits, we compare digits from left to right."
}
Your code should compact to this:
CmsService::SearchContentPractiseProblems.form_fields.each do |field|
answer_fields = %w[answer_a answer_b answer_c answer_d]
row field[:key] do
key = field[:key].to_s
if answer_fields.include?(key)
content['answers'][key]
else
content[key]
end
end
end
Please test it.
%w[abc]
is equivalent to ["a", "b", "c"]
in Ruby
if-else-end
control structure just returns something at the end of the day, so
row field[:key] do
if condition
something
else
something_else
end
end
is equivalent to
if condition
row field[:key] do
something
end
else
row field[:key] do
something_else
end
end
but the first one is more compact and less error-prone
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.