我正在尝试使用符号数组,
a = [:apple, :banana ,:grape, :black]
,并根据最后一个字母在每个符号的末尾添加一个字符串。如果符号以e
结尾,则添加"hello"
,否则添加"hi"
。我想得到:
[:applehello, :bananahi]
我做到了:
n = []
a.each do |b|
if (b[-1] == "e")
n.push b.to_s + "hello"
else
n.push b.to_s + "hi"
end
end
p n
我必须将其转换为字符串。如何获得以符号表示的最终输出?
是否还使用sub-
a.each do |q|
if (q[-1]=="e")
then n.push q.to_s.sub(/e/,"ehello")
else
n.push q.to_s.sub(/\z/,"ahi")
end
end
p n
答案 0 :(得分:4)
使用to_sym
返回符号
a = [:apple, :banana , :grape, :black]
a.map do |s|
(s.to_s + (s[-1] == 'e' ? 'hello' : 'hi')).to_sym
end
替代
a = [:apple, :banana , :grape, :black]
a.map do |s|
"#{s}#{s[-1] == 'e' ? 'hello' : 'hi'}".to_sym
end
答案 1 :(得分:1)
尝试以下,
data have ;
ncandidates=1; ngames=3; controlppt=1; controlgame=2;
ppt1='Abc'; ppt2='Bcd';
infile cards dsd dlm='|';
input (var1-var21) ($);
cards;
1|2|a|1|3|b1|2|a|1|3|b1|2|a|1|3|b1|2|a|1|3|b
1|2|a|1|3|b1|2|a|1|3|b1|2|a|1|3|b1|2|a|1|3|b
;
filename report '~/myreport.txt';
data _null_;
file report dsd dlm='|' LRECL=8614;
a='';
put
83*'#'
/ '##### Number of ppts'
/ 83*'#'
/ 'input.Name=' @
;
eof = 0;
do until(eof);
set have end=eof;
If not missing(var1) then
put var1-var10 @@ ;
end;
put a
// 83*'#'
/ '##### Output Data'
/ 83* '#'
// 'output.Name=' @;
eof2=0;
do until(eof2);
set have end=eof2;
If not missing(var11) then
put var11-var20 @@ ;
end;
put '1';
stop;
run;
答案 2 :(得分:0)
a.map{|sym| sym.to_s.sub(/.\z/) do
|c| case c; when "e" then "hello"; else "hi" end.to_sym
end}
# => [:applhello, :bananhi, :graphello, :blachi]