Besides dynamic input, what makes Ruby “more flexible” than Java?

I have been using Java almost since it first appeared, but over the past five years I have gotten burning with how difficult it is to get even the simplest things. I begin to study Ruby on the recommendation of my psychiatrist, I mean my colleagues (younger, colder employees - they use Makov!). Anyway, one of the things that they keep repeating is that Ruby is a “flexible” language compared to older, more battered languages ​​like Java, but I really don't know what that means. Can someone explain what makes one language “more flexible” than another? You are welcome. I kind of understand the essence of dynamic typing and see how this can be useful for brevity. And the Ruby syntax is, well, beautiful. What else? Is dynamic typing the main reason?

+3
source share
7 answers

Dynamic typing does not come close to closing it. For one great example, Ruby simplifies metaprogramming in many cases. In Java, metaprogramming is either painful or impossible.

For example, take Ruby the usual way of declaring properties:

class SoftDrink
  attr_accessor :name, :sugar_content
end
# Now we can do...
can = SoftDrink.new
can.name = 'Coke' # Not a direct ivar access — calls can.name=('Coke')
can.sugar_content = 9001 # Ditto

This is not some special language syntax - it is a method of the Module class, and it is easy to implement. Here's an example implementation attr_accessor:

class Module
  def attr_accessor(*symbols)
    symbols.each do |symbol|
      define_method(symbol) {instance_variable_get "@#{symbol}"}
      define_method("#{symbol}=") {|val| instance_varible_set("@#{symbol}", val)}
    end
  end
end

This functionality allows you a lot, yes, flexibility in how you express your programs.

, ( ), Ruby. , :

dependencies = %w(yaml haml hpricot sinatra couchfoo)
block_list %w(couchfoo) # Wait, we don't really want CouchDB!
dependencies.each {|mod| require mod unless block_list.include? mod}
+6

, ( Java), - ( ), , , - , " ". Ruby , , . / mixins, . , Ruby, , Java, , ( ), C ( ), , Ruby .

+6

, , . , , , . _, , , , .. , . , Java, , :

def get_all_pending
  scheduled_collections.select{ |sc| sc.is_pending? }
end

:

[0,1,2,3].select{|x| x > 1}

[2,3]

+5

,

  • , .
  • (Proc, lambdas) - . [1, 2, 3].each{|x| puts "Next element #{x}"}
  • PERL.. n , , et.
  • API , Hash Array, .
  • (- ) - DSL (, Rails DSL WebApps, Ruby)
  • , .
+4

. Ruby .

+2

Duck typing , , , . , Ruby , IO, . , , IO ( , ).

, , Java, . , . , Java ( / ). Ruby , ; . , , .

+2

, :

class Fixnum
  def +(other)
    self - other
  end
end

puts 5 + 3
# => 2
+2

Source: https://habr.com/ru/post/1705921/


All Articles