Skip to content

Instantly share code, notes, and snippets.

@davidmason
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidmason/6d467298484a60ff18a3 to your computer and use it in GitHub Desktop.
Save davidmason/6d467298484a60ff18a3 to your computer and use it in GitHub Desktop.
Learning some basics of Ruby functions. Try it in http://repl.it/languages/Ruby
# This evening I got Ally (https://github.com/AllyG) to
# show me some basics for methods/functions in Ruby.
# I still have some major gaps in my mental model of all
# this, but I feel like I know a lot more than I did this
# morning.
def haldo name
puts "Haldo " + name
end
def goodbine name
puts "Adios la Vista, " + name
end
def greetAll (people, greeting)
people.each { |name| greeting.call(name) }
end
def allGreet (people, greets)
greets.each {
|greet| greetAll(people, greet)
}
end
people = Array["Ally", "David", "Wills", "Sassy"]
greetings = Array[
# I think method() turns a module method into
# a function. This and lambdas are the only
# ways I know to get first-class functions.
method(:haldo),
method(:goodbine),
-> (name) { puts name + " is a hooman." },
# I can define this later in the file, and it
# still works.
professor
]
allGreet(people, greetings)
# It seems I can use things earlier in the file than
# their definition. Not sure what mechanism is used
# for that.
professor = -> (name) { puts "Good news " + name + "!" }
puts foo.call(5)
# Newer syntax for lambdas
foo = -> (x) { x * x }
# Older lambda syntax
bar = lambda {|x| 10 * x }
# The return value of the script seems to be the value
# of the last statement in the script
puts bar.call(5)
# Started learning about modules and classes.
# TOo many tickles to finish it tonight. πŸ‘‹πŸ‘‰πŸ˜†πŸ™ŒπŸ‘‹πŸ˜‚πŸ‘‰πŸ‘‹πŸ‘‹πŸ˜­
# - how to define modules
# module name must start with a capital
module MyModule
def MyModule.apple
puts 'Apple!'
end
# Class name must start with capital
class MyClass
def initialize name
@name = name
puts 'Hello, I am a new MyClass'
end
def otherMethod
puts "This is the other method, #{@name}."
end
end
end
# - how to access/use things that are defined in modules
# - how to define classes
# - how to make instances of classes
# Call the 'new' method. This calls initialize.
MyModule.apple()
myMyClass = MyModule::MyClass.new 'David'
myMyClass.otherMethod
# - how to make subclasses (if that is possible)
# - how to extend classes with new functionality (if that is possible
# cooking module
def scramble_food type
if type.is_a? String
puts type
else
puts "Not a food"
end
end
# string manipulation module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment