Skip to content

Instantly share code, notes, and snippets.

@bjelline
Created August 25, 2012 07:25
Show Gist options
  • Save bjelline/3462049 to your computer and use it in GitHub Desktop.
Save bjelline/3462049 to your computer and use it in GitHub Desktop.
Ruby Syntax - tiny examples
# encoding: utf-8
puts true ? "terärer operator funktioniert" : "ternärer operator funktioniert nicht"
# ohne klammern:
puts true || false ? "oder mit || funktioniert hier" : "oder mit || funktioniert hier nicht"
puts true && false ? "und mit && funktioniert hier nicht" : "und mit && funktioniert hier"
# mit klammern:
puts (true || false) ? "oder mit || funktioniert hier" : "oder mit || funktioniert hier nicht"
puts (true && false) ? "und mit && funktioniert hier nicht" : "und mit && funktioniert hier"
# ohne klammern - funktioniert nicht wie erwartet!
puts true or false ? "oder mit or funktioniert hier" : "oder mit or funktioniert hier nicht"
puts true and false ? "und mit and funktioniert hier nicht" : "und mit and funktioniert hier"
# ohne klammern - um zu verdeutlichen, warums nicht funktioniert!
puts true or (false ? "oder mit or funktioniert hier" : "oder mit or funktioniert hier nicht")
puts true and (false ? "und mit and funktioniert hier nicht" : "und mit and funktioniert hier")
# mit klammern - hier erzwingen wir, dass es richtig funktioniert
puts (true or false) ? "oder mit or funktioniert hier" : "oder mit or funktioniert hier nicht"
puts (true and false) ? "und mit and funktioniert hier nicht" : "und mit and funktioniert hier"
# encoding: utf-8
größe = 10
puts größe
default_value = "gray"
# input_value has never been mentioned before...
v = defined?(input_value) ? input_value : default_value
puts "no input at all: the value is #{v}"
input_value = nil
v = input_value || default_value
puts "no input: the value is #{v}"
input_value = "red"
v = input_value || default_value
puts "input: the value is #{v}"
imgdir = ARGV[0]
if imgdir.nil?
puts "programm should be called with one arg: directory containing images"
exit
end
unless File.directory?( imgdir )
puts "programm should be called with one arg: directory containing images"
exit
end
files = Dir[ "#{imgdir}/*.jpg", "#{imgdir}/*.gif", "#{imgdir}/*.png" ]
files.each do |f|
puts "es gibt ein Bild #{f}"
end
cookies = 1..10
puts cookies.include? 2.4
puts cookies.include? 2..4
# encoding: utf-8
languages = ['sh', 'perl', 'ruby', 'python', 'php']
for l in languages
puts "#{l} ist auch eine schöne sprache"
end
puts "das war's für #{l}!"
languages.each { |i| puts "#{i} ist auch eine schöne sprache" }
languages.each do |i|
puts "#{i} ist auch eine schöne sprache"
end
puts "das war's für #{i}!"
def time_this
puts "Code started at #{Time.now}"
yield
puts "Code ended at #{Time.now}"
end
time_this { sleep 1.0 }
def time_multiple( no )
puts "Code started at #{Time.now}"
(1..no).each do
yield
end
puts "Code ended at #{Time.now}"
end
time_multiple(5) { sleep 0.2 }
time_multiple(5) do
sleep 0.2
end
#!/usr/bin/env ruby
require 'rubygems'
require 'mechanize'
class IFBrowser < Mechanize
def get_kurse ( s )
begin
url = "http://www.informatica-feminale.de/Sommer2012/pro/#{s}.html"
page = get( url )
puts page.title
page.search("#content .schwarzboldtitel").each do |t|
puts t.content
end
rescue => e
$stderr.puts "Failed: #{e.class}: #{e.message} #{e.backtrace[0]} #{e.backtrace[1]}"
end
end
end
b = IFBrowser.new
b.get_kurse( "Web" )
exit
puts "hallo wer bist du?"
name = gets
puts "hallo #{name}"
puts "hallo " + name + " wie geht es dir"
puts "sag mir eine zahl"
nr = gets
puts "das gibt #{42 * nr.to_f}"
class Card
@@colors = [ :red, :green, :purple ]
@@form = [ :oval, :squiggle, :rect ]
@@count = [ :one, :two, :three ]
@@fill = [ :empty, :gray, :full ]
def self.whole_deck
all = []
@@colors.each do |c|
@@form.each do |f|
@@count.each do |no|
@@fill.each do |i|
all << Card.new( :color => c, :form => f, :count => no, :fill => i )
end
end
end
end
return all
end
def self.set?( a,b,c )
return false if a.form == b.form and a.form != c.form
return false if a.form == c.form and a.form != b.form
return false if b.form == c.form and a.form != b.form
return false if a.color == b.color and a.color != c.color
return false if a.color == c.color and a.color != b.color
return false if b.color == c.color and a.color != b.color
return false if a.count == b.count and a.count != c.count
return false if a.count == c.count and a.count != b.count
return false if b.count == c.count and a.count != b.count
return false if a.fill == b.fill and a.fill != c.fill
return false if a.fill == c.fill and a.fill != b.fill
return false if b.fill == c.fill and a.fill != b.fill
return true
end
def initialize( h )
raise ArgumentError.new("new Cards must have all 4 attributes (as a hash)") unless h.keys.count == 4
raise ArgumentError.new("new Cards must have :color") unless @@colors.include? h[:color]
raise ArgumentError.new("new Cards must have :form") unless @@form.include? h[:form]
raise ArgumentError.new("new Cards must have :count") unless @@count.include? h[:count]
raise ArgumentError.new("new Cards must have :fill") unless @@fill.include? h[:fill]
@values = h
end
def form
return @values[:form]
end
def color
return @values[:color]
end
def count
return @values[:count]
end
def fill
return @values[:fill]
end
def to_s
"[#{@values[:count]} #{@values[:color]} #{@values[:fill]} #{@values[:form]}]"
end
end
# ein deck mit allen karten erzeugen
deck = Card.whole_deck.shuffle
# immer drei abheben, und schauen ob es ein set ist
while( deck.length > 2 )
a,b,c = deck.shift(3)
puts "#{a} #{b} #{c} ist ein Set!" if Card.set?(a,b,c)
end
# encoding: utf-8
# selbst gewählter Variablen-Name: s
s = 'ich bin blos text, mit #$"% comic-book-flüchen ;-)'
puts s
a = 42
s = "Ich bin Text mit Variablen wie #{a} und Expressions wie #{a.to_s.reverse} drinnen."
puts s
url = 'http://slides.html5rocks.com'
s = <<-EOM
Ich bin ein riesiger klumpen Text
und ende erst, wenn der (selbst gewählte) Bezeichner EOM
alleine auf einer Zeile steht.
<h1>Die Zahl #{a}</h1>
<p>Zum Beispiel kann man das gut verwenden,
wenn man <a href="#{url}">HTML</a> ausgeben will.</p>
EOM
puts s
squares = (1..10).to_a.select {|x| x%2==0}.map { |x| x*x }
puts "result is #{squares} ... but how did that happen?"
(1..10) .tap {|x| puts "original: #{x.inspect}"}
.to_a .tap {|x| puts "array: #{x.inspect}"}
.select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"}
.map { |x| x*x } .tap {|x| puts "squares: #{x.inspect}"}
zahl = 42 * 3.141 # zahlen-typen werden konvertiert
puts "#{zahl} ist in der Klasse #{zahl.class}"
zahl = 42 * "2".to_i # nur so in ruby
puts "#{zahl} ist in der Klasse #{zahl.class}"
zahl = 42 * "2" # funktioniert in perl, php, javascript, aber nicht in ruby
puts "#{zahl} ist in der Klasse #{zahl.class}"
a = nil
puts "in a ist ein #{a.class}"
a = 41
puts "in a ist ein #{a.class}"
a = "Ein String"
puts "in a ist ein #{a.class}"
a = :get
puts "in a ist ein #{a.class}"
a= false
puts "in a ist ein #{a.class}"
a = [1, 2, 3, 'dies', 'und', 'das']
puts "in a ist ein #{a.class}"
a = { 'dies' => 42, 'das' => 'auch'}
puts "in a ist ein #{a.class}"
require 'rubygems'
require 'sinatra'
set :public_folder, 'public/'
get '/hello/:name' do
"<h1>Hello #{params[:name]}</h1>"
end
get '/' do
return <<EOT
<h1>Hello world!</h1>
<ul>
<li><a href="/hello/Rosa">1</a></li>
<li><a href="/hello/Martina">2</a></li>
<li><a href="/hello/Jenny">3</a></li>
<li><a href="/hello/Ida">4</a></li>
<li><a href="/hello/Lena">5</a></li>
<li><a href="/hello/Brigitte">6</a></li>
</ul>
EOT
end
languages = ['sh', 'perl', 'ruby', 'python', 'php']
languages.each do |i|
case i
when "php"
puts "#{i} ist nicht so eine eine schöne sprache"
when "ruby"
puts "#{i} ist die beste von allen"
else
puts "#{i} ist auch eine schöne sprache"
end
end
# encoding: utf-8
testcases = [ Array.new, String.new ]
testcases.each do |i|
case i
when Array
puts "#{i} ist ein Array"
when File
puts "#{i} ist ein file"
else
puts "#{i} hat classe #{i.class}"
end
end
# encoding: utf-8
# monkey patching
module Enumerable
def puts_all
s = inject("") {|string, element| string + ", " + element.to_s}
s.slice!(0..1)
puts s
print "\n"
end
end
letters = %w[a b c d e f g h i j k l m n o p q r s t u v w x y z]
languages = %w[Fortran Ada C C++ Java Scala Haskell Go C# Lisp Pascal Clojure Erlang PHP Python Ruby JRuby Perl]
puts "Eingabe: die Buchstaben"
letters.puts_all
puts "Der nächste Buchstabe zu jedem Buchstaben"
letters.collect(&:succ).puts_all
puts ""
puts "Eingabe: die Sprachen"
languages.puts_all
puts "Eingabe: die Sprachen sortiert"
languages.sort.puts_all
puts "Eingabe: die Sprachen sortiert, nur die ersten 3"
languages.sort.first(3).puts_all
puts "Die Sprache gross geschrieben"
languages.sort.collect { |x| x.upcase }.puts_all
puts "Die Sprache gross geschrieben und sortiert"
languages.sort.collect(&:upcase).sort.puts_all
puts "Das Original ist noch ok"
languages.puts_all
o = %w(dies und das)
puts o.class
r = 1..10
puts r.class
a = r.to_a
puts a.class
# rng === obj → true or false
#
# Returns true if obj is an element of rng, false otherwise.
# Conveniently, === is the comparison operator used by case statements.
case 79
when 1..50 then print "low\n"
when 51..75 then print "medium\n"
when 76..100 then print "high\n"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment