What Is the Ruby Equivalent of the "This" Function in Java

What is the Ruby equivalent of the this function in Java?

The equivalent is self. It is also implict. So self.first_name is the same as first_name within the class unless you are making an assignment.

class Book
attr_reader :first_name, :last_name

def full_name
# this is the same as self.first_name + ", " + self.last_name
first_name + ", " + last_name
end
end

When making an assignment you need to use self explicitly since Ruby has no way of knowing if you are assigning a local variable called first_name or assigning to instance.first_name.

class Book    
def foo
self.first_name = "Bar"
end
end

What's the equivalent of ruby blocks in java

How to do this in Java?

There is no equivalent to Ruby blocks in Java. Ruby blocks are syntactically lightweight, semantically lightweight, and they are not objects. They are mostly syntactic constructions with some lightweight semantics behind. In this, they are more like an enhanced for loop in Java.

The closest equivalent you have in Java, would be a functional interface combined with a lambda expression. Something like this, using one of the pre-defined functional interfaces from the java.util.function package, namely the interface java.util.function.Consumer<T>:

void myf(int i, java.util.function.Consumer<Integer> proc) {
System.out.println("start");
proc.accept(i);
System.out.println("end");
}

You use it like this:

myf(3, i -> System.out.println(i * 10));
myf(4, i -> System.out.println(i - 10));
// start
// 30
// end
// start
// -6
// end

However, this is not equivalent to Ruby's blocks. This is equivalent to Ruby's Procs and lambda literals, in other words, it is more equivalent to this:

def myf(i, proc)
puts "start"
proc.(i)
puts "end"
end

myf(3, -> i { puts i * 10 })
myf(4, -> i { puts i - 10 })

# start
# 30
# end
# start
# -6
# end

Note that myf in your example does not use the result of the block, so modeling it with java.util.function.Function<T, R> would be incorrect. Consumer<T> is the correct interface to use for a "function" (more a procedure, really) that "consumes" its argument but doesn't return anything, whereas Function<T, R> is the correct interface to use for a function that takes one argument and returns a result.

What is Java function equivalent to Ruby Object#inspect

I guess what you want is ReflectionToStringBuilder in Apache Commons Lang library.

In your class, define your inspect() method like as follows, and you should be able to see the expected result:

public void inspect() {
System.out.println(ReflectionToStringBuilder.toString(this));
}

Equivalent of Ruby #map or #collect in Java?

There's the map method on streams which takes a method argument.

collection.stream()
.map(obj -> obj.someMethod())
.collect(Collectors.toList()));

map returns another stream so in order to retrieve the list you have call the collect method.

Too much to explain in a post, but you can visit this link which helped me out a lot:

http://winterbe.com/posts/2014/03/16/java-8-tutorial/

Equivalent of Ruby Hash in Java

HashMap<String, Integer> map = new HashMap<>();
map.put("test", 1);

I assume?

What is java interface equivalent in Ruby?

Ruby has Interfaces just like any other language.

Note that you have to be careful not to conflate the concept of the Interface, which is an abstract specification of the responsibilities, guarantees and protocols of a unit with the concept of the interface which is a keyword in the Java, C# and VB.NET programming languages. In Ruby, we use the former all the time, but the latter simply doesn't exist.

It is very important to distinguish the two. What's important is the Interface, not the interface. The interface tells you pretty much nothing useful. Nothing demonstrates this better than the marker interfaces in Java, which are interfaces that have no members at all: just take a look at java.io.Serializable and java.lang.Cloneable; those two interfaces mean very different things, yet they have the exact same signature.

So, if two interfaces that mean different things, have the same signature, what exactly is the interface even guaranteeing you?

Another good example:

package java.util;

interface List<E> implements Collection<E>, Iterable<E> {
void add(int index, E element)
throws UnsupportedOperationException, ClassCastException,
NullPointerException, IllegalArgumentException,
IndexOutOfBoundsException;
}

What is the Interface of java.util.List<E>.add?

  • that the length of the collection does not decrease
  • that all the items that were in the collection before are still there
  • that element is in the collection

And which of those actually shows up in the interface? None! There is nothing in the interface that says that the Add method must even add at all, it might just as well remove an element from the collection.

This is a perfectly valid implementation of that interface:

class MyCollection<E> implements java.util.List<E> {
void add(int index, E element)
throws UnsupportedOperationException, ClassCastException,
NullPointerException, IllegalArgumentException,
IndexOutOfBoundsException {
remove(element);
}
}

Another example: where in java.util.Set<E> does it actually say that it is, you know, a set? Nowhere! Or more precisely, in the documentation. In English.

In pretty much all cases of interfaces, both from Java and .NET, all the relevant information is actually in the docs, not in the types. So, if the types don't tell you anything interesting anyway, why keep them at all? Why not stick just to documentation? And that's exactly what Ruby does.

Note that there are other languages in which the Interface can actually be described in a meaningful way. However, those languages typically don't call the construct which describes the Interface "interface", they call it type. In a dependently-typed programming language, you can, for example, express the properties that a sort function returns a collection of the same length as the original, that every element which is in the original is also in the sorted collection and that no bigger element appears before a smaller element.

So, in short: Ruby does not have an equivalent to a Java interface. It does, however, have an equivalent to a Java Interface, and it's exactly the same as in Java: documentation.

Also, just like in Java, Acceptance Tests can be used to specify Interfaces as well.

In particular, in Ruby, the Interface of an object is determined by what it can do, not what class is is, or what module it mixes in. Any object that has a << method can be appended to. This is very useful in unit tests, where you can simply pass in an Array or a String instead of a more complicated Logger, even though Array and Logger do not share an explicit interface apart from the fact that they both have a method called <<.

Another example is StringIO, which implements the same Interface as IO and thus a large portion of the Interface of File, but without sharing any common ancestor besides Object.

To convert ruby unpack equivalent in java

So I'm going to break this down. The first step is token.unpack('m0'). According to Idiosyncratic Ruby unpack('m0') will decode base64, similarly to the built-in Base64 libararies Base64.decode64(string) function. But unpack returns an arry here, with only 1 element, the converted base64. So we use token.unpack('m0').first to get the first (and in this case the only) element of the array returned by token.unpack('m0'). If this was all, then you'd be correct to say that it's just base64. But, the unpacked base64 is unpacked again, this time with 'H*', which will convert the characters to hex. And finally, because that will return an array, you use first again to make it only a string.

So in summary, what is happening is that first your string is being decoded from base64 to a string, then it's being converted to hex.

Is there a Java equivalent to if __FILE__ == $0?

java has the public static void main(String[] args) method. this is invoked when a class is run as the main class from the command line, and generally only invoked in such a scenario (you could call it directly, but it usually doesn't make sense). so, in java, the standard is to put "main invocation" logic in this method.

Is there a Ruby version of for-loop similar to the one on Java/C++?

Yes you can use each_with_index

collection = ["element1", "element2"]
collection.each_with_index {|item,index| puts item; puts index}

the 'index' variable gives you the element index during each iteration

Java has FindBugs. What is equivalent for Ruby?

Take a look at this blog. It talks about different tools (Roodi, Dust and Flog).



Related Topics



Leave a reply



Submit