phonebook = {
"Jonas" => "123456",
"Sara" => "654321" }
phonebook["Jacob"] = "987654"
puts phonebook["Jonas"]
var phonebook = Map(
"Jonas" -> "123456",
"Sara" -> "654321")
phonebook += ("Jacob" -> "987654")
println(phonebook("Jonas"))
class String
def any?(&b)
enum_for(:each_char).any?(&b)
end
def upcase?
self == self.upcase
end
end
"Sam".any? &:upcase?
"Sam".exists(_.isUpperCase)
NOTE: Yes, it's not a very fair example to compare a built-in (Scala) to not (Ruby), but it's idiomatic and the code I would (did) write off the top of my head (without the benefit of profiling or anything, after all, it's about the syntax here).
class Person
attr_accessor :name, :age
def initialize(name, age)
@name, @age = name, age
end
end
class Person(var name:String, var age:Int)
class Person
attr_reader :name, :age
end
class Person {
val name:Option[String] = None
val age:Option[Int] = None
}
NOTE: The above doesn't make a ton of sense in either case since there's no methods declared that would actually set the value of the variables as a side-effect. It's purely a syntax example, just a portion of any real-world implementation needing getters.
module Foo
def bar
"baz"
end
end
class Zed
include Foo
end
puts Zed.new.bar
trait Foo { def bar = "baz" }
class Zed extends Foo
println(new Zed().bar)
module Foo
def bar
"baz"
end
end
class Alpha
end
# If you need a var:
# alpha = Alpha.new
# alpha.extend Foo
# puts alpha.bar
puts Alpha.new.extend(Foo).bar
trait Foo { def bar = "baz" }
class Alpha
// If you need a var:
// val alpha = new Alpha() with Foo
// println(alpha.bar)
println(new Alpha() with Foo bar)
NOTE: I realize some people might claim shenanigans with some of the Scala one-liners. My rationale is simple: For the given code, I've tried to demonstrate appropriately idiomatic code. It's entirely possible to write this in Ruby for example:
But you're not likely to ever actually run into code like that in the wild. Rubyists don't like semi-colons. Ditto for Scala developers AFAICT, so even though it would be entirely possible to write:
I've yet to run into any examples written that way.
The one purposeful exception to language idioms here is the use of
#extend
in the Singleton Class (per-instance) Mixins example for Ruby. Usage of#extend
outside of DSL libraries is so rare as is, and I just thought it was a neat one-liner to calltarget.extend(MyModule).some_method
since#extend
returnsself
.