首页 文章

操纵红宝石中的符号

提问于
浏览
0

我想尝试一系列符号,

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

3 回答

  • 1

    尝试以下,

    a.map { |x| "#{x}#{x.to_s.last == 'e' ? 'hello' : 'hi'}".to_sym }
    # => [:applehello, :bananahi, :grapehello, :blackhi]
    
  • 1
    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]
    
  • 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
    

相关问题