Rafeh Ishtiaq
Rafeh Ishtiaq

Reputation: 113

Manipulating symbols in ruby

I am trying to take an array of symbols,

a = [:apple, :banana ,:grape, :black]

and add a string at the end of each symbol depending on the last letter. If the symbol ends with e, add "hello", otherwise "hi". I want to get:

[:applehello, :bananahi]

I did:

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

I have to convert it into strings. How can I get the final output in symbols?

Did it using sub aswell-

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

Upvotes: 0

Views: 377

Answers (3)

sawa
sawa

Reputation: 168071

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]

Upvotes: 0

ray
ray

Reputation: 5552

Tried with following,

a.map { |x| "#{x}#{x.to_s.last == 'e' ? 'hello' : 'hi'}".to_sym }
# => [:applehello, :bananahi, :grapehello, :blackhi]

Upvotes: 1

Ursus
Ursus

Reputation: 30056

Use to_sym to have a symbol back

a = [:apple, :banana , :grape, :black]
a.map do |s|
  (s.to_s + (s[-1] == 'e' ? 'hello' : 'hi')).to_sym
end

An alternative

a = [:apple, :banana , :grape, :black]
a.map do |s|
  "#{s}#{s[-1] == 'e' ? 'hello' : 'hi'}".to_sym
end

Upvotes: 4

Related Questions