3 Replies - 455 Views - Last Post: 01 June 2014 - 09:10 AM Rate Topic: -----

#1 roelof1967  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 01-June 14

how to do this more the ruby way

Posted 01 June 2014 - 01:00 AM

Hello,

Suppose I have a variable word with the contents of "dog"

Now I want to look against a - z which letters are avaible.

I can do this :

 
for (a..z).to_a.each do |letter| 
    if word.include? (letter) 
         puts "The letter #{letter} is in the word"
    else 
         puts "The letter #{letter} is not in the word"
    end
end



but this look not very rubbisch way to solve this ?

Can anyone give me a tip how to do this more the rubbisch way /

Roelof

Is This A Good Question/Topic? 0
  • +

Replies To: how to do this more the ruby way

#2 Lemur  Icon User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1359
  • View blog
  • Posts: 3,425
  • Joined: 28-November 09

Re: how to do this more the ruby way

Posted 01 June 2014 - 08:12 AM

word.downcase.chars & ('a'..'z').to_a # In both (Intersection)
('a'..'z').to_a - word.downcase.chars # Not in word (Difference)



Set theory
Was This Post Helpful? 1
  • +
  • -

#3 roelof1967  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 01-June 14

Re: how to do this more the ruby way

Posted 01 June 2014 - 08:28 AM

View PostLemur, on 01 June 2014 - 08:12 AM, said:

word.downcase.chars & ('a'..'z').to_a # In both (Intersection)
('a'..'z').to_a - word.downcase.chars # Not in word (Difference)



Set theory


one question.

How do I put the text that a letter is in the word.
and how do I know which letters are in in both.

Roelof

When I do "dog".downcase.chars & ('a'..'z').to_a I do not see any output.

Roelof
Was This Post Helpful? 0
  • +
  • -

#4 Lemur  Icon User is offline

  • Pragmatism over Dogma
  • member icon


Reputation: 1359
  • View blog
  • Posts: 3,425
  • Joined: 28-November 09

Re: how to do this more the ruby way

Posted 01 June 2014 - 09:10 AM

It returns an array, you have to print that.

[2] pry(main)> 'dog'.downcase.chars & ('a'..'z').to_a
=> ["d", "o", "g"]
[3] pry(main)> ('a'..'z').to_a - 'dog'.downcase.chars
=> ["a",
 "b",
 "c",
 "e",
 "f",
 "h",
 "i",
 "j",
 "k",
 "l",
 "m",
 "n",
 "p",
 "q",
 "r",
 "s",
 "t",
 "u",
 "v",
 "w",
 "x",
 "y",
 "z"]


This post has been edited by Lemur: 01 June 2014 - 09:12 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1