577 Matching Annotations
  1. Nov 2020
  2. Oct 2020
    1. Probably wouldn't work for capybara-based tests where it forks a different process for the web server?

    1. However, if perform was creating threads and you ended up with closures inside perform, then you could end up with several threads referencing the same local variables captured through the closures. So you do have to be careful about scope issues when you create threads but you don't have to worry about it when dealing with simple methods that only work with local variables

      Однако, если выполнение создавало потоки, и вы закончили с замыканиями внутри выполнения, тогда вы могли бы получить несколько потоков, ссылающихся на одни и те же локальные переменные, захваченные с помощью замыканий. Таким образом, вы должны быть осторожны с проблемами области при создании потоков, но вам не нужно беспокоиться об этом при работе с простыми методами, которые работают только с локальными переменными.

    2. The local variables, such as your hash, are local to the particular invocation of the surrounding method. If two threads end up calling perform at the same time, then each call will get its own execution context and those won't overlap unless there are shared resources involved: instance variables (@hash), class variables (@@hash), globals ($hash), ... can cause concurrency problems. There's nothing to worry about thread-wise with something simple like your perform.

      Локальные переменные, такие как ваш хэш, являются локальными для конкретного вызова окружающего метода. Если два потока вызывают выполнение одновременно, то каждый вызов получит свой собственный контекст выполнения, и они не будут перекрываться, если не задействованы общие ресурсы: переменные экземпляра (@hash), переменные класса (@@ hash), глобальные переменные. ($ hash), ... может вызвать проблемы параллелизма. Не нужно беспокоиться о потоковой передаче с чем-то простым, например, с вашей работой.

  3. Sep 2020
  4. Aug 2020
    1. Ruby is the programming language used in Translation Proxy. For Sarah, Object Oriented Design “done the Ruby way” is so enjoyable and is the part of her work that she likes most.
  5. Jul 2020
    1. Ruby has some really nice libraries for working with linked data. These libraries allow you to work with the data in both a graph and resource-oriented fashion, allowing a developer to use the techniques that best suit his or her use cases and skills.
    1. Since Ruby 1.9.2, Time implementation uses a signed 63 bit integer, Bignum or Rational. The integer is a number of nanoseconds since the Epoch which can represent 1823-11-12 to 2116-02-20. When Bignum or Rational is used (before 1823, after 2116, under nanosecond), Time works slower as when integer is used.
    1. There is a usability problem here, it's basically impossible to read the output of Time#inspect in such a case, even though the input was readable.
    2. So, which is better? t.inspect # => "2007-11-01 15:25:00 8483885939586761/68719476736000000 UTC" t.inspect # => "2007-11-01 15:25:00.123456789000000004307366907596588134765625 UTC"
    1. Introducing Module#const_source_locationUsing Method#source_location made finding the location of any method fairly easy. Unfortunately, there wasn’t an equivalent for constants. This meant that unless the constant you needed to find was defined in your codebase, finding its source location was not easy.
    1. Enumerable#tally is added. It counts the occurrence of each element. ["a", "b", "c", "b"].tally #=> {"a"=>1, "b"=>2, "c"=>1}
    2. Enumerator::Lazy#eager is added. It generates a non-lazy enumerator from a lazy enumerator.
    3. A beginless range is experimentally introduced. It might not be as useful as an endless range, but would be good for DSL purposes.
    1. It does change it, but it makes it much simpler in my opinion. It is basically "the receiver is statically the explicit literal special variable self or implicit." This gets rid of the current exception for private writer methods (self.foo = bar).
    1. Why don't you allow a range without end, like (1..)? There are two advantages. First, we can write ary[1..] instead of ary[1..-1]. The -1 is one of the most I dislike in Ruby. It is very magical, ugly, redundant, and disappointing. I envy Python's ary[1:]. I know that ary.drop(1) is slightly fast, but too long for such a common operation, IMO. Second, we can write (1..).each {|n| ... }.
    1. require 'set' class Array def uniq_elements(&prc) prc ||= ->(e) { e } uniques, dups = {}, Set.new each do |e| k = prc[e] ((uniques.key?(k)) ? (dups << k; uniques.delete(k)) : uniques[k] = e) unless dups.include?(k) end uniques.values end end
    1. To me the difference between [1,1,2,2,3,3] and [1,2,3] is not []
    2. It’s even worse that there’s no alternative method that does the unsurprising thing IMO.
    3. Are you angry now? Because I’m angry.
    4. You should see me doing a write up for a Ruby feature suggestion only to discover that Array#- is hijacked for non-mathematical reasons
    5. Oh. Oh no. That's... not a thing that should be. People wonder why we can't get be more popular with science / math academics.
    6. I don't think this is a good overload of 'subtraction'1Olivier Lacan@olivierlacan·Jan 14, 2019Yup. I don’t either.
    7. but not as two methods called Array#- and Array#difference. As something like Array#set_difference maybe, or even Array#subtract_all, maybe.
    1. One may expect Array#- to behave like mathematical subtraction or difference when it doesn't. One could be forgiven to expect the following behavior: [1,1,2,2,3,3,4,4] - [1,2,3,4] => [1,2,3,4]
    2. I'll freely admit I was surprised by this behavior myself since I needed to obtain an Array with only one instance of each item in the argument array removed.
    1. If you answer is yes, then we are doing this wrong because subset? or part_of method should be in a parent class (maybe Enumerable class ) in order for it to work for subset, array, hash and any data structure that inherit from it Enumerable.
    1. Arrays are not sets. Trying to treat them as if they are is an error, and will create subtle problems. What should be the result of the following operations? [1, 1] | [1] [1] | [1, 1] Of course, there are more interesting examples. These two are to get you started. I don't care what the results currently are. I don't care what you think they should be. I can present extremely strong arguments for various answers. For this reason, I believe that #| is an ill-defined concept. Generalizing an ill-defined concept is a world of pain. If you insist on treating objects of one class as if they were members of a different class, there should be bumps in the road to at least warn you that maybe this is a bad idea. I'm not going to argue that we should remove or deprecate #|. I don't think of myself as a fanatic. But encouraging this sort of abuse of the type system just creates problems.
    2. I do not understand why concat modify the array, as most of the method of the Array class has a ! method for that. Should I also introduced a concat! method?
  6. Jun 2020
    1. What would be nice is if JavaScript had a built-in way to do what I can do in Ruby with:

      > I18n.interpolate('Hi, %{name}', name: 'Fred')
      => "Hi, Fred"
      

      But to be fair, I18n comes from i18n library, so JS could just as easily (and I'm sure does) have a library that does the same thing.

      Update: Actually, you can do this in plain Ruby (so why do we even need I18n.interpolate?):

      main > "Hi, %{name}" % {name: 'Fred'}
      => "Hi, Fred"
      
      main > ? String#%
      
      From: string.c (C Method):
      Owner: String
      Visibility: public
      Signature: %(arg1)
      Number of lines: 9
      
      Format---Uses str as a format specification, and returns the result
      of applying it to arg. If the format specification contains more than
      one substitution, then arg must be an Array or Hash
      containing the values to be substituted. See Kernel::sprintf for
      details of the format string.
      
         "%05d" % 123                              #=> "00123"
         "%-5s: %016x" % [ "ID", self.object_id ]  #=> "ID   : 00002b054ec93168"
         "foo = %{foo}" % { :foo => 'bar' }        #=> "foo = bar"
      

      I guess that built-in version is fine for simple cases. You only need to use I18n.translate if you need its more advanced features like I18n.config.missing_interpolation_argument_handler.

  7. May 2020
    1. However, distributing such Ruby apps to inexperienced end users or non-Ruby-programmer end users is problematic. If users have to install Ruby first, or if they have to use RubyGems, they can easily run into problems. Even if they already have Ruby installed, they can still run into problems, e.g. by having the wrong Ruby version installed. The point is, it's a very real problem that could harm your reputation.
    1. Programming languages These will probably expose my ignorance pretty nicely.

      When to use different programming languages (advice from an Amazon employee):

      • Java - enterprise applications
      • C# - Microsoft's spin on Java (useful in the Microsoft's ecosystem)
      • Ruby - when speed is more important then legibility or debugging
      • Python - same as Ruby but also for ML/AI (don't forget to use type hinting to make life a little saner)
      • Go/Rust - fresh web service where latency and performance were more important than community/library support
      • Haskell/Erlang - for very elegant/mathematical functional approach without a lot of business logic
      • Clojure - in situation when you love Lisp (?)
      • Kotlin/Scala - languages compiling to JVM bytecode (preferable over Clojure). Kotlin works with Java and has great IntelliJ support
      • C - classes of applications (operating systems, language design, low-level programming and hardware)
      • C++ - robotics, video games and high frequency trading where the performance gains from no garbage collection make it preferable to Java
      • PHP/Hack - testing server changes without rebuilding. PHP is banned at Amazon due to security reasons, but its successor, Hack, runs a lot of Facebook and Slack's backends
  8. Apr 2020
    1. The method name is generated by replacing spaces with underscores. The result does not need to be a valid Ruby identifier though, the name may contain punctuation characters etc. That's because in Ruby technically any string may be a method name. This may require use of define_method and send calls to function properly, but formally there's little restriction on the name.
    1. But where is the helper method defined? What’s its visibility? Can I put it in a module? Can I use inheritance? Who can call it? Can I call super from the extracted method? If so, where does super go?
    1. minitest doesn't reinvent anything that ruby already provides, like: classes, modules, inheritance, methods. This means you only have to learn ruby to use minitest and all of your regular OO practices like extract-method refactorings still apply.
    1. This situation usually arises from external constraints not design choices such as my example with Sequel. My point is that assigning a value to a constant is allowed by Ruby in certain scopes and not others. It used to be up to the developer to choose wisely when to perform the assignment. Ruby changed on this. Not for everyone's good.
    1. The handler can be a method or a Proc object passed to the :with option. You can also use a block directly instead of an explicit Proc object.

      Example of: letting you either pass a proc (as a keyword arg in this case) or as a block.

  9. Mar 2020
    1. Ruby's current handling of Dates and Times is all over the map. We have Date, Time, DateTime, ParseDate, and more, not to mention all the other common extensions running around out there. Ruby needs an improved class that incorporates them all.
    1. Methods must be tested both via a Lemon unit test and as a QED demo. The Lemon unit tests are for testing a method in detail whereas the QED demos are for demonstrating usage.
    1. prepend_message
    2. To be just a bit polemic, your first instinct was not to do that. And you probably wouldn't think of that in your unit tests either (the holy grail of dynamic langs). So someday it would blow up at runtime, and THEN you'd add that safeguard.
    3. As many would guess: ... catch StandardError => e raise $! ... raises the same error referenced by $!, the same as simply calling: ... catch StandardError => e raise ... but probably not for the reasons one might think. In this case, the call to raise is NOT just raising the object in $!...it raises the result of $!.exception(nil), which in this case happens to be $!.
    1. The pattern below has become exceptionally useful for me (pun intended). It's clean, can be easily modularized, and the errors are expressive. Within my class I define new errors that inherit from StandardError, and I raise them with messages (for example, the object associated with the error).
    1. The popular question in my company these days is “Rails or WordPress?”, but I will probably touch upon the broader questions of “MVC or CMS?” and “Ruby or PHP?”, so you can often substitute “Rails” for “MVC framework” in the article.
  10. Feb 2020
    1. Returns an indication of the number of arguments accepted by a method. Returns a nonnegative integer for methods that take a fixed number of arguments. For Ruby methods that take a variable number of arguments, returns -n-1, where n is the number of required arguments. Keyword arguments will be considered as a single additional argument, that argument being mandatory if any keyword argument is mandatory. For methods written in C, returns -1 if the call takes a variable number of arguments.

      What they fail to mention is that apparently the arity is always -1 if the method is available dynamically (due to respond_to_missing?).

  11. Jan 2020
    1. I've often wished for some standard variable to use for blocks and such. Like some people here, I had considered it. Usually I use _ but I know that means "unused" to many/most programmers. I like the % option that Clojure has.

  12. Dec 2019
  13. Nov 2019
    1. Example of someone else defining a file that simply requires another file because this is the one that gem (?) or bundler (?) looks for when your gem is named activerecord-pg_enum

  14. Oct 2019
  15. Sep 2019
  16. Aug 2019
  17. Feb 2019
  18. Jan 2016
    1. require 'active_record/connection_adapters/postgis_adapter/railtie'

      The following worked better in my setup:

      require 'active_record/connection_adapters/postgis/railtie'
      
    1. with another instance as its receiver

      An instance can call private methods of another instance of the same class.

  19. Nov 2015
    1. まぶた)

      Testing a highlight on Ruby text.

      Highlight is meant to wrap this image: kanji

      Highlight is also meant to include the super-script hiragana characters: まぶた

      Actual highlight includes the hiragana characters "まぶた" as well as ")"

  20. Jul 2015
  21. May 2015
    1. Just to focus on the differences between lambdas and Procs, a lambda acts more like a real method. What does that mean?

      Apparently it means a lambda is less ($@(#$ insane.

    2. When you create your own function to accept procs, the guts need to change a little bit because you'll need to use #call instead of yield inside (because which proc would yield run if you had more than one?).

      Too much special!! Why the special cases? Just so that one can type yield instead of invoking a function and naming the argument?

    3. Use that block of code (now called a Proc) as an input to a function by prepending it with an apersand &

      Oh, Ruby. This is entirely too confusing. Why is the ampersand required to signify that something is passed as a block, especially given that it has a type (Proc)? What does it mean if the ampersand isn't used?