Ruby :: Aufgabe #16

2 Lösungen Lösungen öffentlich

Vokale zählen in einem beliebigen Satz

Anfänger - Ruby von Dome - 28.12.2012 um 23:58 Uhr
Programmieren Sie ein Programm, welches die Anzahl aller Vokale in einem zuvor eingegebenen Satz ausgibt.
Optional wäre die Ausgabe wie oft welcher Vokal in dem Satz vorhanden ist.

Konsolenausgabe:


Geben Sie einen Satz ein :
Dies ist ein toller Satz.
Anzahl der Vokale : 8
A: 1
E: 3
I: 3
O: 1
U: 0

Lösungen:

vote_ok
von pianoplayer (1330 Punkte) - 06.12.2013 um 17:38 Uhr
Quellcode ausblenden Ruby-Code
#schlichte Implementierung
print "Geben Sie einen Satz ein: "
satz = gets.chomp.downcase
a=satz.count("a")
e=satz.count("e")
i=satz.count("i")
o=satz.count("o")
u=satz.count("u")
puts "Anzahl der Vokale: #{a + e + i + + o + u}"
puts "A: #{a}"
puts "E: #{e}"
puts "I: #{i}"
puts "O: #{o}"
puts "U: #{u}"

#alternative, etwas kryptische Implementierung
print "Geben Sie einen Satz ein: "
satz = gets.chomp.upcase
vokale = ["A","E","I","O","U"]
anzahl = []
vokale.each { |i| anzahl << satz.count(i) }
puts "Anzahl der Vokale: #{anzahl.inject(0) { |sum,n| sum + n }}"
for i in 0..4 do
  puts "#{vokale[i]}: #{anzahl[i]}"
end 
vote_ok
von Idef1x (1320 Punkte) - 23.01.2018 um 17:26 Uhr
Quellcode ausblenden Ruby-Code
=begin
 T.y.P. #16 Count vowels
 By Lars I.
 Lines of code:     6
=end

#============================================================================================

def vowels(str)
=begin
 In:
  - 
 
 Out:
  - 
  
=end

#Section - CODE
 
 #Section - Declaration
    
    vows = {"a" => 0 , "e" => 0 , "i" => 0 , "o" => 0 , "u" => 0 }
    
 #Section - Count 
    
    str.each_char { |char| char == "a" || char == "e" || char == "i" || char == "o" || char == "u" ? vows[char] += 1 : "" }
    
 #Section - Output
    
    vows.each_pair { |key, val| print "#{key}:\t#{val}\n" }
 
end

str = gets.chomp

vowels(str)